Arrays
JavaScript arrays are collection types that behave similarly to Python’s lists. They allow you to store multiple items sequentially inside a single variable.
Creating Arrays
Unlike many strictly-typed programming languages, items inside a JavaScript array are not required to be of the same type. You can mix strings, numbers, and booleans freely.
const numbers = [1, 2, 3, 4, 5];
const strings = ["banana", "apple", "pear"];
const miscellaneous = [true, 7, "adamantium"];
Accessing Elements
You can access individual items within an array using zero-based indexing via square brackets [].
const strings = ["banana", "apple", "pear"];
console.log(strings[0]); // Output: "banana"
console.log(strings[2]); // Output: "pear"
Adding Elements
You can dynamically add new items to the end of an array using the built-in .push() method.
const drinks = [];
drinks.push("lemonade");
console.log(drinks); // Output: ["lemonade"]
drinks.push("root beer");
console.log(drinks); // Output: ["lemonade", "root beer"]