
Hi guys, you know JavaScript has these two interesting methods shift() and unshift(). Read on to find out what are Javascript shift() and unshift() methods and how you can use these two methods.
Let’s see first what this shift() method in javascript is and how can you use the javascript shift() method.
Javascript shift() method – When you have to remove the first element from a javascript array then you can use the shift method. What happens here is that shift() method remove the first element and shift all the other element to a lower index.
let’s see it with an example –
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript shift() Method</h1>
<p id="demoId1"></p>
<p id="demoId2"></p>
<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];
document.getElementById("demoId1").innerHTML = cars;
cars.shift();
document.getElementById("demoId2").innerHTML = cars;
</script>
</body>
</html>
Output :
JavaScript shift() Method
Porsche,BMW,Audi,Jaguar
BMW,Audi,Jaguar
See the output before calling shift() method. Before calling the shift method Porsche was at index 0, BMW at index 1, Audi at index 2, and, Jaguar at index 3. And after calling the shift() method on the cars array the three elements moved to lower index. Now BMW is at index 0, Audi is at index 1 and jaguar is at index 2.
Now let’s see javascript unshift() method.
JavaScript unshift() method –
You use JavaScript unshift() method if you want to add a new element at the beginning of an array. Here, unshift() method moves older elements to a higher index.
Let’s see it with an example.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript unshift() Method</h1>
<p id="demoId1"></p>
<p id="demoId2"></p>
<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];
document.getElementById("demoId1").innerHTML = cars;
cars.unshift("Bentley");
document.getElementById("demoId2").innerHTML = cars;
</script>
</body>
</html>
Output :
JavaScript unshift() Method
Porsche,BMW,Audi,Jaguar
Bentley,Porsche,BMW,Audi,Jaguar
Here, unshift() method moved older elements to higher index and added a new element Bentley at the beginning of the cars array.
That’s all about Javascript shift() and unshift() methods.
Have any question in mind?
Comment below.
Goodbye.
Leave a Reply