Javascript Array unshift()

Introduction

Javascript array unshift() method adds one or more elements to the beginning of an array.

It returns the new length of the array.

arr.unshift(element1[, ...[, elementN]])
  • elementN - the elements to add to the front of the array.

Add new items to the beginning of an array:

var languages = ["CSS", "HTML", "Java", "Javascript"];
console.log(languages);//from   w ww.j  av  a2 s.  c o m

languages.unshift("SQL", "Java");
console.log(languages);
let arr = [4, 5, 6];
console.log(arr);/* www .j  a v a  2 s .c o m*/
arr.unshift(1, 2, 3);
console.log(arr);// [1, 2, 3, 4, 5, 6]

arr = [4, 5, 6];
arr.unshift(1);
console.log(arr);
arr.unshift(2);
console.log(arr);
arr.unshift(3);
console.log(arr);// [3, 2, 1, 4, 5, 6]

arr = [1, 2];
arr.unshift([-4, -3]);// [[-4, -3], -2, -1, 0, 1, 2]

More example:

let colors = new Array(); // create an array 
let count = colors.unshift("red", "green"); // push two items 
console.log(count); // 2 

count = colors.unshift("black"); // push another item on 
console.log(count); // 3 

let item = colors.pop(); // get the first item 
console.log(item); // "green" 
console.log(colors.length); // 2 



PreviousNext

Related