Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What benefit do you get in javascript declaring an array with a specific length? [duplicate]

Tags:

javascript

In most javascript apps I usually declare an array like so

var x = [];

but I've seen a ton of example code on MDN that take this approach instead

var x = new Array(10);

With V8/other modern JS engines, do you see a real benefit one way or the other?

like image 466
Toran Billups Avatar asked Apr 19 '14 20:04

Toran Billups


People also ask

What does length 10 mean in a JavaScript array?

In this case {length: 10} represents the minimal definition of an "array-like" object: an empty object with just a length property defined. Array.from allows for a second argument to map over the resulting array.

How to declare an array in JavaScript?

Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements. Declaration of an Array. There are basically two ways to declare an array. Example: var House = [ ]; // method 1. var House = new array (); // method 2. But generally method 1 is preferred over ...

When should I use arrays and objects in JavaScript?

When to Use Arrays. When to use Objects. JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

How to initialize an array's length in JavaScript?

How to initialize an array's length in JavaScript? Most of the tutorials that I've read on arrays in JavaScript (including w3schools and devguru) suggest that you can initialize an array with a certain length by passing an integer to the Array constructor using the var test = new Array (4); syntax.


1 Answers

None. Javascript doesn’t implement real arrays. It all gets abstracted through javascript object notation.

So say:

a = [0, 1];
b = {"0": 1, "1": 1};

Has the same effect:

a[0] //0
b[0] //0

One more thing to keep in mind is when you do:

a[100] = 100;

The length gets automagically set to 101. Even though:

a[2] //undefined
like image 183
beautifulcoder Avatar answered Nov 05 '22 21:11

beautifulcoder