Push , Pop, Shift and Unshift ๐ช
All the hidden secrets are under the table. Keep revising! ๐
push
, pop
, shift
, and unshift
are four common methods used to manipulate the contents of an array in many programming languages. Here are some examples of how they work:
push
: Thepush
method adds one or more elements to the end of an array. For example:
scssCopy codelet myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
In this example, the push
method adds the value 4
to the end of the myArray
array.
pop
: Thepop
method removes the last element from an array and returns it. For example:
javascriptCopy codelet myArray = [1, 2, 3];
let poppedValue = myArray.pop();
console.log(poppedValue); // Output: 3
console.log(myArray); // Output: [1, 2]
In this example, the pop
method removes the last element, 3
, from the myArray
array and assigns it to the poppedValue
variable.
shift
: Theshift
method removes the first element from an array and returns it. For example:
javascriptCopy codelet myArray = [1, 2, 3];
let shiftedValue = myArray.shift();
console.log(shiftedValue); // Output: 1
console.log(myArray); // Output: [2, 3]
In this example, the shift
method removes the first element, 1
, from the myArray
array and assigns it to the shiftedValue
variable.
unshift
: Theunshift
method adds one or more elements to the beginning of an array. For example:
scssCopy codelet myArray = [1, 2, 3];
myArray.unshift(0, -1);
console.log(myArray); // Output: [0, -1, 1, 2, 3]
In this example, the unshift
method adds the values 0
and -1
to the beginning of the myArray
array.
ย