Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create slice.md #5

Merged
merged 1 commit into from
Oct 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions en/arrays/slice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
chapter: 6
pageNumber: 48
description: The Javascript arr.slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.
---
# Slice

The `slice` method accepts two parameters begin and end.
* begin: This parameter defines the starting index from where the portion is to be extracted.
If this argument is missing then the method takes begin as 0 as it is the default start value.
* end: This parameter is the index up to which the portion is to be extracted (excluding the end index).
If this argument is not defined then the array till the end is extracted as it is the default end value If the end value is greater than the length of the array, then the end value changes to the length of the array.

```javascript
function func() {
//Original Array
let arr = [23, 56, 87, 32, 75, 13];
//Extracted array
let new_arr = arr.slice();
console.log(arr);
console.log(new_arr);
}
func();


// RESULT:
[23,56,87,32,75,13]
[23,56,87,32,75,13]
```

The `slice()` method copies object references to the new array.
(For example, a nested array) So if the referenced object is modified, the changes are visible in the returned new array.

```javascript
let human = {
name: "David",
age: 23,
};

let arr = [human, "Nepal", "Manager"];
let new_arr = arr.slice();

// original object
console.log(arr[0]); // { name: 'David', age: 23 }

// making changes to the object in new array
new_arr[0].name = "Levy";

// changes are reflected
console.log(arr[0]); // { name: 'Levy', age: 23 }
```