Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the unshift() method?

Sarvech Qadir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The unshift() method adds new items to the beginning of an array. This method changes the length of the array and returns the new length of the array.

Syntax

array.unshift(item1, item2,...)

Code

<p>Clicking on the button will add items to start of array.</p>
<button onclick="myfunc()">Click</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
// given an array of chocolates
var choc = ["Hersheys", "Kitkat", "Snickers"];
document.getElementById("demo").innerHTML = choc;
function myfunc() {
// the function adds these chocolate names to the start of array
x = choc.unshift("Twix", "Mars");
document.getElementById("demo").innerHTML = choc;
document.getElementById("demo1").innerHTML = x;
}
</script>

RELATED TAGS

javascript

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring