JavaScript

June 7, 2023

How to use JavaScript Array splice()

Program to use JavaScript Array splice() method


let a = [1, 2, 3, 7, 5];
let b = a.splice(3, 1, 4);

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

Output


[1, 2, 3, 4, 5]
[7]

Steps Description

  1. Declare two variable a and b
  2. Initialize two variable with value of array a = [1, 2, 3, 7, 5] and b = a.splice(3, 1, 4)
  3. Array splice() method adds or removes an array element and returns the removed element.
  4. The value of b variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array splice() method


let c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20];
let d = c.splice(1, 2, 4, 6)

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

Output


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

Steps Description

  1. Declare two variable c and d
  2. Initialize two variable with value of array c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20] and d = c.splice(1, 2, 4, 6)
  3. Array splice() method adds or removes an array element and returns the removed element.
  4. The value of d variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array splice() method


let e = ['Cat', 'Dog', 'Tiger', 'Lion'];
let f = e.splice(2, 0, 'Elephant', 'Bear');

console.log(e);
console.log(f);

Output


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

Steps Description

  1. Declare two variable e and f
  2. Initialize two variable with value of array e = ['Cat', 'Dog', 'Tiger', 'Lion'] and f = e.splice(2, 0, 'Elephant', 'Bear')
  3. Array splice() method adds or removes an array element and returns the removed element.
  4. The value of f variable is displayed with the help of console.log inbuilt function

by : Suhel Akhtar

Quick Summary:

Array element can be added and removed in JavaScript array splice() method