Array literals
array literal notation is where you define a new array using just empty brackets.var myArray = [];
It is the “new” way of defining arrays, and I suppose it is shorter/cleaner.
The examples below explain the difference between them:
1 | var a = [], // these are the same |
Methods
- forEach
- map
- push // add to the end
- unshift // add to the front
- pop // remove from the end
- shift // remove from the front
- splice // remove
- slice // sub array
Array.length
how Array length property works
- Reading the length
1) For a dense array, this means that the length corresponds strictly to the number of elements:
1 | var fruits = ['orange', 'apple', 'banana']; //fruits is a dense array |
The dense array does not have empties and the number of items corresponds to highestIndex + 1. In [3, 5, 7, 8] the highest index is 3 of element 8, thus the array size is 3 + 1 = 4.
2) In a sparse array (which has empties), the number of elements does not correspond to length value, but still is determined by the highest index:
1 | var animals = ['cat', 'dog', , 'monkey']; // animals is sparse |
- Modifying the length
1) Modifying the property leads to cut the elements (if the new value is smaller than the highest index):
1 | var numbers = [1, 3, 5, 7, 8]; |
2) or creating a sparse array (if the new value is bigger than the highest index):
1 | var osTypes = ['OS X', 'Linux', 'Windows']; |