1var colors = ["white","blue"];
2colors.unshift("red"); //add red to beginning of colors
3// colors = ["red","white","blue"]
1//Add element to front of array
2var numbers = ["2", "3", "4", "5"];
3numbers.unshift("1");
4//Result - numbers: ["1", "2", "3", "4", "5"]
1//The unshift() method adds one or more elements to the beginning of an array
2//and returns the new length of the array.
3
4const array1 = [1, 2, 3];
5console.log(array1.unshift(4, 5));
6// expected output: 5
7console.log(array1);
8// expected output: Array [4, 5, 1, 2, 3]
1var name = [ "john" ];
2name.unshift( "charlie" );
3name.unshift( "joseph", "Jane" );
4console.log(name);
5
6//Output will be
7[" joseph "," Jane ", " charlie ", " john "]
1let newLength = fruits.unshift('Strawberry') // add to the front
2// ["Strawberry", "Banana"]
3
1// Use unshift method if you don't mind mutating issue
2// If you want to avoid mutating issue
3const array = [3, 2, 1]
4
5const newFirstElement = 4
6
7const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
8
9console.log(newArray);
10