How to Use push(), unshift(),pop() and shift() With Array in Javascript?

28-Jun-2023

.

Admin

How to Use push(), unshift(),pop() and shift() With Array in Javascript?

Today, javascript array shift() is our main topic. This post will give you simple example of unshift(). you'll learn push() and pop() methods. step by step explain push. Let's see bellow example pop.

push(): The push() method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.

Example:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use push(), unshift(),pop() and shift() With Array in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let fruits = ['apple', 'banana'];

fruits.push('orange', 'grape');

console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape']

</script>

</html>

unshift(): The unshift() method is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.

Example:

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use push(), unshift(),pop() and shift() With Array in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let fruits = ['apple', 'banana'];

fruits.unshift('orange', 'grape');

console.log(fruits); // Output: ['orange', 'grape', 'apple', 'banana']

</script>

</html>

pop(): The pop() method is used to remove the last element from an array. It modifies the original array and returns the removed element.

Example 3:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use push(), unshift(),pop() and shift() With Array in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let fruits = ['apple', 'banana'];

let removedFruit = fruits.pop();

console.log(removedFruit); // Output: banana

console.log(fruits); // Output: ['apple']

</script>

</html>

shift(): The shift() method is used to remove the first element from an array. It modifies the original array and returns the removed element.

Example 4:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to Use push(), unshift(),pop() and shift() With Array in Javascript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

let fruits = ['apple', 'banana'];

let removedFruit = fruits.shift();

console.log(removedFruit); // Output: apple

console.log(fruits); // Output: ['banana']

</script>

</html>

#JavaScript