I want to create an array in javascript and remember two ways of doing it so I just want to know what the fundamental differences are and if there is a performance difference in these two "styles"
var array_1 = new Array("fee","fie","foo","fum"); var array_2 = ['a','b','c']; for (let i=0; i<array_1.length; i++){ console.log(array_1[i]) } for (let i=0; i<array_2.length; i++){ console.log(array_2[i]) }
Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.
As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).
An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.
They do the same thing. Advantages to the []
notation are:
Array
symbol, it still works.new Array(3)
, if you're used to seeing entries listed in the constructor, you could easily misread that to mean [3]
, when in fact it creates a new array with a length
of 3 and no entries.new Array
, the interpreter has to go look up the Array
symbol, which means traversing all entries in the scope chain until it gets to the global object and finds it, whereas with []
it doesn't need to do that. The odds of that having any tangible real-world impact in normal use cases are low. Still, though...So there are several good reasons to use []
.
Advantages to new Array
:
var a = new Array(3);
I haven't had any reason to do that in several years (not since learning that arrays aren't really arrays and there's no point trying to pre-allocate them). And if you really want to, you can always do this:
var a = []; a.length = 3;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With