Arrays
An array is an ordered, changeable collection — JavaScript's equivalent of Python's list, and probably the most-used data structure in the language.
main.js
Try it yourself →let fruits = ["apple", "banana", "cherry"];
console.log(fruits);
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);
fruits.push("date");
console.log(fruits);
fruits.pop();
console.log(fruits);
console.log(fruits.length);Output
[ 'apple', 'banana', 'cherry' ] apple cherry [ 'apple', 'banana', 'cherry', 'date' ] [ 'apple', 'banana', 'cherry' ] 3
- fruits[0] gets the first item — unlike Python, JavaScript has no negative indexing, so fruits[fruits.length - 1] is how you get the last item
- push() adds an item to the end of the array, in place
- pop() removes and returns the last item
- length is a property that always reflects the array's current size
Sorting — and a real gotcha
main.js
Try it yourself →let numbers = [5, 3, 1, 4, 2]; numbers.sort(); console.log(numbers); numbers.reverse(); console.log(numbers);
Output
[ 1, 2, 3, 4, 5 ] [ 5, 4, 3, 2, 1 ]
That looks right — but sort() actually converts elements to strings and compares them alphabetically by default, which happens to give the correct order for single digits. It breaks as soon as a number has more than one digit:
main.js
Try it yourself →let bigNumbers = [10, 1, 21, 2]; bigNumbers.sort(); console.log(bigNumbers);
Output
[ 1, 10, 2, 21 ]
"10" sorts before "2" alphabetically, the same way "apple" sorts before "banana" — that's genuinely what happened here. To sort numbers correctly, pass a comparator function: numbers.sort((a, b) => a - b).
Next: objects — storing values by name instead of by position.
Practice exercise
Create colors = ["red", "green", "blue"]. Push "yellow" onto it, then print the array.