How to use JavaScript Array slice()

Program to use JavaScript Array slice() method


let a = [ 'Cat', 'Dog', 'Tiger', 'Lion', 'Elephant' ];

let b = a.slice(1,4);

console.log('String slice =',b);

Output


String slice = [ 'Dog', 'Tiger', 'Lion' ]

Steps Description

  1. Declare two variable a and b
  2. Initialize two variable a and b with value of array let a = [ 'Cat', 'Dog', 'Tiger', 'Lion', 'Elephant' ] and b
  3. slice() method is used to slice the array by giving index number
  4. The value of b variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array slice() method with multiplication table


let c = [ 3,6,9,12,15,18,21,24,27,30 ];

let d = c.slice(5);

console.log('String slice =',d);

Output


String slice = [ 18, 21, 24, 27, 30 ]

Steps Description

  1. Declare two variable c and d
  2. Initialize two variable c and d with value of array let c = [ 3,6,9,12,15,18,21,24,27,30 ] and d
  3. slice() method is used to slice the array by giving index number
  4. The value of d variable is displayed with the help of console.log inbuilt function

Program to use JavaScript Array slice() method with count


let e = [ 1,2,3,4,5,6,7,8,9,10 ];

let f = e.slice(3,6);

console.log('String slice =',f);

Output


String slice = [ 4, 5, 6 ]

Steps Description

  1. Declare two variable e and f
  2. Initialize two variable e and f with value of array let e = [ 1,2,3,4,5,6,7,8,9,10 ] and f
  3. slice() method is used to slice the array by giving index number
  4. The value of f variable is displayed with the help of console.log inbuilt function