Declare a new array in JavaScript with a var as its size

totally new to JS but need to use it atm.

In C language I can declare new arrays the following way: int A[10], B[A];

This way I can create custom sized arrays of a variable.

Is it possible to do the same with JavaScript? I need to make an Array with the size of a variable.
I tried to do stuff like: var n = 10; var A = new Array(n); but it just doesn’t work.
Thanks.

81 thoughts on “Declare a new array in JavaScript with a var as its size”

  1. Either

    Array(n)
    

    or

    Array.from({length: n})  // Creates array from array-like or iterable.
    

    But it’s still possible to push new items.

    let arr = Array(5)  // [empty x 5]
    arr[25] = 10        // [empty x 25, 10]
    
    Reply

Leave a Comment