All VideosJavaScript Tutorials

What is Slice in JavaScript | JavaScript Tutorials in Hindi | Interview Question #51

In JavaScript, the slice method is used to create a shallow copy of a portion of an array or a string. This method does not modify the original array or string, but instead returns a new array or string with the selected elements.

Syntax for Arrays:

array.slice(beginIndex, endIndex)

beginIndex: The index at which to begin extraction. If this is negative, it begins that many elements from the end.

endIndex: The index at which to end extraction. The element at this index is not included. If omitted, it extracts through the end of the array. If negative, it indicates an offset from the end of the array.

Example for Arrays:

let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
let citrus = fruits.slice(1, 3); // ['Banana', 'Cherry']

Syntax for Strings:

string.slice(beginIndex, endIndex)

beginIndex: The index at which to begin extraction. If negative, it is treated as string.length + beginIndex.

endIndex: The index at which to end extraction. If negative, it is treated as string.length + endIndex. If omitted, it extracts to the end of the string.

Example for Strings:

let text = "Hello, world!";
let greeting = text.slice(0, 5); // 'Hello'

Key Points:

he slice method does not alter the original array or string.
When used on arrays, the slice method returns a new array.
When used on strings, the slice method returns a new string.
Both beginIndex and endIndex can be negative, counting from the end of the array or string.

Practical Uses:

Extracting a portion of an array or string without modifying the original.
Creating a copy of an array or string for further manipulation.
Implementing array or string-based algorithms where a subset of elements is needed.

Example with Negative Indices:

let animals = ['Dog', 'Cat', 'Elephant', 'Tiger', 'Lion'];
let lastTwo = animals.slice(-2); // ['Tiger', 'Lion']

let phrase = "JavaScript";
let lastPart = phrase.slice(-6); // 'Script'

The slice method is a powerful and versatile tool in JavaScript for handling arrays and strings efficiently.

Leave a Reply

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

error: Content is protected !!