Topic 42 of 87
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
Push and Pop (The End of the Array)
javascript
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"]Join and toString
javascript
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
Q:
What does
Array.prototype.pop() return?A:
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.
example
javascript
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.