Arrays and Array Methods
Storing Lists of Data
If you need to store 100 usernames, you wouldn't create 100 different variables. Instead, you use an Array. An array is a special variable that can hold more than one value at a time.
let frameworks = ["React", "Next.js", "Vue"];
console.log(frameworks[0]); // Outputs: "React" (Arrays are zero-indexed!)
Essential Array Methods
Arrays come with built-in methods that make managing lists incredibly easy.
1. push() and pop()
push()adds a new item to the end of the array.pop()removes the last item from the end of the array.
let stack = ["HTML", "CSS"];
stack.push("JavaScript"); // ["HTML", "CSS", "JavaScript"]
stack.pop(); // Removes "JavaScript"
2. unshift() and shift()
unshift()adds a new item to the beginning of the array.shift()removes the first item from the beginning of the array.
3. length Just like strings, you can find the size of an array:
console.log(stack.length);
4. join() Converts an array into a string, separated by whatever character you choose.
let names = ["Himanshu", "Dubey"];
console.log(names.join(" ")); // "Himanshu Dubey"
💡 Himanshu's Tip:
When you use const to declare an array, you can still push() or pop() items! const only prevents you from completely reassigning the variable to a brand new array. Always declare your arrays with const.
Interview Questions
- How do you access the last element of an array if you don't know its exact length?
- What is the difference between
push()andunshift(), and which one is faster in terms of performance? - Can a single JavaScript array hold mixed data types (e.g., Numbers and Strings together)?