Push Pop Unshift Shift Array Javascript
In JavaScript, shift, unshift, push, and pop are array methods used to add or remove elements. Here's a quick breakdown:
1. push()
- Adds one or more elements to the end of an array
- Returns the new array length.
- Example:
const fruits = ["apple", "banana"];
fruits.push("cherry");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
2. pop()
- Removes the last element from an array
- Returns that element.
- Example:
const fruits = ["apple", "banana", "cherry"];
const last = fruits.pop();
console.log(fruits); // Output: ["apple", "banana"]
console.log(last); // Output: "cherry"
3. unshift()
- Adds one or more elements to the beginning of an array and returns the new array length.
- Example:
const fruits = ["banana", "cherry"];
fruits.unshift("apple");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
4. shift()
- Removes the first element from an array and returns that element.
- Example:
const fruits = ["apple", "banana", "cherry"];
const first = fruits.shift();
console.log(fruits); // Output: ["banana", "cherry"]
console.log(first); // Output: "apple"
Summary
push()andpop()modify the end of the array.unshift()andshift()modify the beginning of the array.