pop()removes an element from the end of an array, whileshift()removes an element from the beginning. The key difference betweenpop()andshift()and their cousinspush()andunshift(), is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.Let's take a look:
function popShift(arr) {
let popped = arr.pop();
let shifted = arr.shift();
return [shifted, popped];
}
console.log(popShift(['challenge', 'is', 'not', 'complete']));
console will display ['challenge', 'complete']
- We defined a function,
popShift, which takes an array as an argument and returns a new array. I modified the function, usingpop()andshift(), to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
Top comments (0)