Creating & Accessing Arrays
Arrays are ordered lists of values. They store multiple items in a single variable — numbers, strings, objects, or even other arrays. Arrays are the most-used data structure in JavaScript.
Array Basics
- Creating — const fruits = ['Apple', 'Banana', 'Cherry']; or new Array(3)
- Indexing — Zero-based: fruits[0] = 'Apple', fruits[1] = 'Banana'
- Length — fruits.length returns the number of items
- Last item — fruits[fruits.length - 1] or fruits.at(-1) (ES2022)
- Mixed types — Arrays can hold any type: [1, 'hello', true, null, {name: 'Alice'}]
- Check if array — Array.isArray(value) returns true/false
Array Basics Code
// Creating arrays
const fruits = ["Apple", "Banana", "Cherry", "Date"];
const numbers = [10, 20, 30, 40, 50];
const mixed = [1, "hello", true, null, { name: "Alice" }];
// Accessing elements (0-indexed)
console.log(fruits[0]); // "Apple"
console.log(fruits[2]); // "Cherry"
console.log(fruits.at(-1)); // "Date" (last item, ES2022)
// Length
console.log(fruits.length); // 4
// Modifying
fruits[1] = "Blueberry";
console.log(fruits); // ["Apple", "Blueberry", "Cherry", "Date"]
// Check type
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray("hello")); // false
console.log(typeof fruits); // "object" (arrays are objects!)
// Empty array
const empty = [];
console.log(empty.length); // 0Tip
Tip
Use .at(-1) to get the last element instead of arr[arr.length - 1]. It's cleaner and works with any negative index: arr.at(-2) gets the second-to-last element. Available in all modern browsers (ES2022).
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Using typeof to check for arrays returns 'object', not 'array'. Always use Array.isArray(value) to reliably check if something is an array. This is because arrays are technically objects in JavaScript.
Practice Task
Note
Create an inventory array: (1) Add 5 product objects with name, price, quantity. (2) Access the first and last items using both bracket notation and .at(). (3) Verify it's an array with Array.isArray(). (4) Log the total count with .length.
Quick Quiz
Key Takeaways
- Arrays are ordered lists of values.
- Creating — const fruits = ['Apple', 'Banana', 'Cherry']; or new Array(3)
- Indexing — Zero-based: fruits[0] = 'Apple', fruits[1] = 'Banana'
- Length — fruits.length returns the number of items