Skip to main content

Command Palette

Search for a command to run...

Push , Pop, Shift and Unshift ๐Ÿช

All the hidden secrets are under the table. Keep revising! ๐Ÿš€

Published
โ€ข2 min readโ€ขView as Markdown
Push , Pop, Shift and Unshift ๐Ÿช
T

Firestone

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:

  1. push: The push 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.

  1. pop: The pop 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.

  1. shift: The shift 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.

  1. unshift: The unshift 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.

More from this blog

Top Gun Maping

14 posts