BackendFrontendJavascriptUncategorizedWeb Development

What is slice() Method in Javascript?

The slice() method is a method that returns a new Array with a subset of the original Array’s elements.

The slice() method is used to return an array of integers. The following code snippet shows how you can use the slice() method to return an array of even numbers from an array of numbers:

var evenNumbers = [1, 2, 3, 4, 5];
var evenNumbersArray = evenNumbers.slice(2); // returns [3, 4, 5]

The slice() method is often used in conjunction with other methods such as map(), reduce(), and filter().

Copy a portion of an array

const colors = ['red','green','blue','yellow','purple'];
const rgbColor = colors.slice(0,3);
console.log(rgbColor); // ["red", "green", "blue"]

Convert array-like objects into arrays

function toNewArray() {
  return Array.prototype.slice.call(arguments);
}

var studentClass = toNewArray('A','B','C');

console.log(studentClass); // ["A", "B", "C"]

Crop a String

const name = 'himanshu';
const newName = name.slice(0, 2);
console.log(newName) // 'him'

 

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button