Array Methods
Overview
Arrays come packed with built-in methods that allow you to manipulate the data without writing complex, manual for loops.
Some of the most basic and frequently used methods include push() and pop() for managing the end of the array, and join() for converting the array into a clean string.
Syntax
const stack = ["HTML", "CSS"];
// push() adds one or more elements to the END
stack.push("JavaScript");
// stack is now ["HTML", "CSS", "JavaScript"]
// pop() removes the LAST element and returns it
const removedItem = stack.pop();
console.log(removedItem); // "JavaScript"
console.log(stack); // ["HTML", "CSS"]const words = ["Hello", "World"];
// toString() joins with commas by default
console.log(words.toString()); // "Hello,World"
// join() lets you specify the separator
console.log(words.join(" ")); // "Hello World"
console.log(words.join(" - ")); // "Hello - World"Common Pitfalls
Thinking
push()returns the new array. A very common bug isconst newArr = oldArr.push('x');.push()actually returns the new length of the array, sonewArrbecomes a number, completely breaking your code.
Interview Questions
What does Array.prototype.pop() return?
It returns the actual element that was removed from the end of the array. If the array is empty, it returns undefined.
Real-World Example
Joining an array of dynamic classes for a React component's className prop.
const classes = ["btn", "btn-primary", isActive ? "active" : ""];
return <button className={classes.join(" ").trim()}>Click</button>Check Your Knowledge
Test your understanding of Array Methods with these quick questions.