javascript array insert at 0 code example

Example 1: javascript add new array element to start of array

var colors = ["white","blue"];
colors.unshift("red"); //add red to beginning of colors
// colors = ["red","white","blue"]

Example 2: javascript array insert at 0

let myArray = [1,2,3];
myArray.unshift(0);
console.log(myArray); // [0,1,2,3]

Example 3: javascript unshift

let array = ["A", "B"];
 let variable = "what you want to add";

//Add the variable to the beginning of the array
 array.unshift(variable);

//===========================
 console.log(array);
//output =>
//["what you want to add" ,"A", "B"]

Example 4: prepend to array javascript

// Build an array of test data.
var data = [ "X" ];

// Unshift data onto the array. Unshift() prepends elements to
// the beginning of the given array. Note that it can take more
// than one argument. In the output, notice that when unshift()
// takes multiple arguments, they are prepended in a right-to-left
// order (mimicing their appearence in the arguments list).
data.unshift( "A" );
data.unshift( "B", "C" );

// Output resultant array.
console.log( data );

Example 5: push at first index typescript

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]