BackendFrontendJavascriptWeb 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

2 Comments

  1. hey

    It’s been a while since our last conversation, but I recently stumbled upon something online about connectdigitalworld.com and thought it important to reach out.

    It seems like there’s some unfavorable news that could be potentially damaging.
    Knowing how quickly rumors can spiral and wishing not you to be caught off guard, I thought it best to warn you.

    I hope it’s all a misunderstanding, but I believed it necessary you should know!

    All the best to you,
    Ulrich

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button