Careeroza
Array Basics
Creating and Accessing Arrays
Example
An array is an ordered list. Indexes start at 0:
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0], fruits.length);
console.log(fruits.at(-1)); // last element
fruits[1] = "Orange";
console.log(fruits);
const mixed = [1, "two", { three: 3 }, [4]];
console.log(mixed.length);Output
Apple 3 Mango [ 'Apple', 'Orange', 'Mango' ] 4
Adding and Removing
| Method | Does | Changes the array? |
|---|---|---|
push(x) / pop() | add / remove at the end | yes |
unshift(x) / shift() | add / remove at the start | yes |
splice(i, n, ...items) | remove/insert anywhere | yes |
slice(start, end) | copy a part | no |
concat(), [...a, ...b] | join arrays | no |
Example
const list = ["a", "b", "c"];
list.push("d");
list.unshift("z");
console.log(list);
console.log(list.pop(), list.shift(), list);
const removed = list.splice(1, 1, "X", "Y");
console.log(removed, list);
console.log(list.slice(0, 2), list);Output
[ 'z', 'a', 'b', 'c', 'd' ] d z [ 'a', 'b', 'c' ] [ 'b' ] [ 'a', 'X', 'Y', 'c' ] [ 'a', 'X' ] [ 'a', 'X', 'Y', 'c' ]