How to use JavaScript Array unshift()

Program to use JavaScript Array unshift() method


let a = [8,10,12,14,16,18,20];
let b = a.unshift(2,4,6);

console.log(a);
console.log(b);

Output


[
    2,  4,  6,  8, 10,
   12, 14, 16, 18, 20
 ]
 10

Steps Description

  1. Declare two variable a and b
  2. Initialize two variable with value of array a = [8,10,12,14,16,18,20] and b = a.unshift(2,4,6)
  3. Array unshift() method appends one or more elements to the beginning of an array and returns the length of the new array.
  4. The value of b variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array unshift() method


let c = [ 'Cat', 'Dog', 'Tiger', 'Lion'];
let d = c.unshift('Elephant', 'Bear');

console.log(c);
console.log(d);

Output


[ 'Elephant', 'Bear', 'Cat', 'Dog', 'Tiger', 'Lion' ]
6

Steps Description

  1. Declare two variable c and d
  2. Initialize two variable with value of array c = [ 'Cat', 'Dog', 'Tiger', 'Lion'] and d = c.unshift('Elephant', 'Bear')
  3. Array unshift() method appends one or more elements to the beginning of an array and returns the length of the new array.
  4. The value of d variable is displayed with the help of console.log inbuilt function