push and unshift in javascript 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: unshift method in javascript
var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);
//Output will be
[" joseph "," Jane ", " charlie ", " john "]
Example 3: 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 4: unshift javascript
/*The unshift() adds method elements to the beginning, and push() method
adds elements to the end of an array.*/
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX');
// now equals ['XIX', 'XX', 'XXI', 'XXII']
romanNumerals.push(twentyThree);
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']
Example 5: js unshift vs push
//My Opinion is really nothing. They are the same exept one adds a element
//to the end and the other one adds a element to the front
// Push Method
var array = [2];//your random array
array.push(3)
// Unshift Method
array.unshift(1)