The shift()
method removes the first element from an array and returns that element.
Example
let languages = ["English", "Java", "Python", "JavaScript"];
// removes the first element of the array
let first = languages.shift();
console.log(first);
console.log(languages);
// Output: English
// [ 'Java', 'Python', 'JavaScript' ]
shift() Syntax
The syntax of the shift()
method is:
arr.shift()
Here, arr is an array.
shift() Parameters
The shift()
method does not accept any arguments.
shift() Return Value
- Removes the first element from
array
and returns that value. - Returns
undefined
if the array is empty.
After removing the element at the 0th index, it shifts other values to consecutive indexes down.
Notes:
- This method changes the original array and its length.
- To remove the last element of an array, use the JavaScript Array pop() method.
Example: Using shift() method
var languages = ["JavaScript", "Python", "Java", "C++", "Lua"];
var shifted = languages.shift();
console.log(languages); // [ 'Python', 'Java', 'C++', 'Lua' ]
console.log(shifted); // JavaScript
// shift returns any type of object
var numbers = [
[1, 2, 3],
[4, 5, 6],
[-5, -4, -3],
];
console.log(numbers.shift()); // [ 1, 2, 3 ]
console.log(numbers); // [ [ 4, 5, 6 ], [ -5, -4, -3 ] ]
Output
[ 'Python', 'Java', 'C++', 'Lua' ] JavaScript [ 1, 2, 3 ] [ [ 4, 5, 6 ], [ -5, -4, -3 ] ]
Also Read: