xxxxxxxxxx
let array = [1, 2, 3, 4, 5]; // Example array
let removedElement = array.shift(); // Remove the first element and store it in a variable
console.log("Removed element:", removedElement); // Output: "Removed element: 1"
console.log("Updated array:", array); // Output: "Updated array: [2, 3, 4, 5]"
xxxxxxxxxx
The shift() method removes the
first element from an array and
returns that removed element.
This method changes the length of the array.
example:
var colors = [ 'red','white', 'blue'];
colors.shift();
console.log(colors)
// colors = [ 'white', 'blue']
var numbers = [1, 2, 3, 4, 5];
numbers.shift();
console.log(numbers);
// numbers: [ 2, 3, 4, 5 ]
xxxxxxxxxx
// example (remove the last element in the array)
let yourArray = ["aaa", "bbb", "ccc", "ddd"];
yourArray.shift(); // yourArray = ["bbb", "ccc", "ddd"]
// syntax:
// <array-name>.shift();
xxxxxxxxxx
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
// var fruits = ["Orange", "Apple", "Mango"];
xxxxxxxxxx
// remove the first element with shift
let flowers = ["Rose", "Lily", "Tulip", "Orchid"];
// assigning shift to a variable is not needed if
// you don't need the first element any longer
let removedFlowers = flowers.shift();
console.log(flowers); // ["Lily", "Tulip", "Orchid"]
console.log(removedFlowers); // "Rose"
xxxxxxxxxx
const arr = ['foo', 'bar', 'qux', 'buz'];
arr.shift(); // 'foo'
arr; // ['bar', 'qux', 'buz']
xxxxxxxxxx
const arr = ['a', 'b', 'c'];
const firstElement = arr.shift();
console.log(firstElement); // a
console.log(arr); // ['b', 'c']
xxxxxxxxxx
var array = [1, 2, 3, 4, 5];
array.shift(); // Remove first element of the array
console.log(array); // Output: [2, 3, 4, 5]
xxxxxxxxxx
var arr = ["f", "o", "o", "b", "a", "r"];
arr.shift();
console.log(arr); // ["o", "o", "b", "a", "r"]