This article is for anyone who has consistently struggled to understand the JavaScript slice
method, or who confuses the slice
with the splice
. If you feel you are that person, jump in as I break it down to you and you gain more clarity. We will be exploring the way it works, step by step.
What Does The Word Slice Mean?
Now what does the word slice mean in English language? slice is a word that is used as a noun and as a verb depending on the context. It usually refers to the cutting of something into thin flat pieces or the appearance of a part of something.
As a noun : It is a portion of something. A thin part or portion.
As a verb : To cut into thin flat pieces.
Slice In Programming
Slice is a method usually attached to arrays and strings in JavaScript (other programming languages have methods for achieving their slice). The slice
method is a method used to extract, preserve and return index values in JavaScript.
Since JavaScript is a high-level programming language which is close to the human language, the writers must have had no problem integrating the slice word into it. The slice is usually used to extract part of an array or string to form new ones respectively.
The slice is commonly used in JavaScript string and array data types. The word slice has been knocking programmers heads together since time immemorial considering its spelling similarity with the splice (another JavaScript method). Don't worry by the end of this text your knowledge would improve.
With Strings
As we know, when dealing with strings in JavaScript, characters like commas, full-stops and spaces are treated as indexes. This index count usually starts from zero (as is done in programming), but when I talk, think and explain positions I like to start my count from one. So for the purpose of this article
index 0 == position 1
.
Note this as it will be very vital to your general understanding of the slice. Below let us see some code.
const str = "My name is Steve"
In the above, M
is our index 0 otherwise written as str[0]
and is our first position. Now the space between My
and name
is index 2 otherwise known as str[2]
, position 3 and y
str[1]
position 2.
Now let us go to the main issue at hand, using the slice
method with strings.
Slice with Single Positive Index
Here our slice
method takes a single positive index.
Counting From 1
In this scenario, we start our count from 1 and not 0.
Syntax
str.slice(chopOffPositions)
The Breakdown
chopOffPositions
is what I like to call my first parameter and I'll show you why
const str = "My name is Steve"
const txt = str.slice(8)
console.log(txt)
//'is Steve'
The length of str
is 16.
const str = "My name is Steve"
console.log(str.length)
Value | position |
---|---|
m | 1 |
y | 2 |
space | 3 |
n | 4 |
a | 5 |
m | 6 |
e | 7 |
space | 8 |
i | 9 |
s | 10 |
space | 11 |
s | 12 |
t | 13 |
e | 14 |
v | 15 |
e | 16 |
So we chop off the first 8 positions which are str[0]
to str[7]
and return "is Steve".
Output
Value | Position |
---|---|
i | 9 |
s | 10 |
space | 11 |
s | 12 |
t | 13 |
e | 14 |
v | 15 |
e | 16 |
Slice with Two Positive Indexes
Occasionally the slice
takes a second parameter which I like to call the chopOffAfter
.
Syntax
str.slice(chopOffPositions, chopOffAfter)
The Breakdown
So what happens is that, it first chops off the number of positions specified in the first parameter then returns the values from the immediate position after, up to the position specified in the second parameter and chops off the rest positions after the second parameter.
const str = "My name is Steve"
const txt = str.slice(8,12)
console.log(txt)
//'is S'
We chopped of the first 8 positions str[0]
to str[7]
and chop off everything after the 12th position str[11]
.
Value | Position |
---|---|
m | 1 |
y | 2 |
space | 3 |
n | 4 |
a | 5 |
m | 6 |
e | 7 |
space | 8 |
i | 9 |
s | 10 |
space | 11 |
s | 12 |
t | 13 |
e | 14 |
v | 15 |
e | 16 |
Output
Value | Position |
---|---|
i | 9 |
s | 10 |
space | 11 |
s | 12 |
Now this above examples are when we count from 1. Next, I will show you how to interpret it with the Count from 0.
Counting From 0
For this examples, we will count from 0.
Syntax
slice(ignoreIndexBefore)
The Breakdown
ignoreIndexBefore
is what I like to call my first parameter, and I'll show you why.
const str = "Hello world"
const text=str.slice(6)
// 'world'
Value | Index |
---|---|
H | 0 |
e | 1 |
l | 2 |
l | 3 |
o | 4 |
space | 5 |
w | 6 |
o | 7 |
r | 8 |
l | 9 |
d | 10 |
What we do is that we ignore every index that comes before the index specified as our argument while it extracts, preserves and returns the values from the index specified.
Output
Value | Index |
---|---|
w | 6 |
O | 7 |
r | 8 |
l | 9 |
d | 10 |
With Second Parameter
Let us see what happens when our slice
takes a second parameter.
Syntax
slice(ignoreIndexBefore,ignoreIndexFrom)
The Breakdown
ignoreIndexFrom
is what I like to call my second parameter and I'll show you why.
const str = "Hello world"
const text=str.slice(6,8)
//'wo'
Value | Index |
---|---|
H | 0 |
e | 1 |
l | 2 |
l | 3 |
o | 4 |
space | 5 |
w | 6 |
o | 7 |
r | 8 |
l | 9 |
d | 10 |
What happens is that we chop off from the index specified as our second argument, after we have chopped off those in our first argument. So we only extract preserve and return our index 6 and index 7.
Output
Value | Index |
---|---|
w | 6 |
o | 7 |
Slice with Single Negative Index
When dealing with slice and negative indexes, there is some difference in the way the index values are extracted.
When dealing with a single negative index,it extracts, preserves and returns the number of indexes attached to the negative sign with the count starting from behind (right to left).
Counting From 1
Now we see what happens when we start our count from 1.
Syntax
str.slice(keepPositions)
The Breakdown
keepPositions
is what I like to call my first parameter and I'll show you why.
const str = "Steve has started cooking."
const text = str.slice(-8)
console.log(text)
//'cooking.'
Value | Position |
---|---|
s | 26 |
t | 25 |
e | 24 |
v | 23 |
e | 22 |
space | 21 |
h | 20 |
a | 19 |
s | 18 |
space | 17 |
s | 16 |
t | 15 |
a | 14 |
r | 13 |
t | 12 |
e | 11 |
d | 10 |
space | 9 |
c | 8 |
o | 7 |
o | 6 |
k | 5 |
i | 4 |
n | 3 |
g | 2 |
. | 1 |
We count backwards starting from .(full-stop) up until c, but rather than chopping them off, in this scenario it returns them.
Output
Value | Position |
---|---|
c | 8 |
o | 7 |
o | 6 |
k | 5 |
i | 4 |
n | 3 |
g | 2 |
. | 1 |
Slice with Two Negative Indexes
The slice method with two negative indexes has the same extract philosophy with our slice with positive index arguments. Except that we count from behind, thereby flipping our two parameters, with the first becoming the second and vice versa.
Counting From 1
Let us see what happens when we count from 1.
Syntax
str.slice(chopOffAfter,chopOffPositions)
The Breakdown
We will be counting from behind(right to left), but in this case we will be following the extract, preserve and return philosophy of the slice with positive indexes.
let str = "Call me dev Steve"
let text=str.slice(-9,-5)
//'dev'
The above code returns dev
and space
,even though we can't see the space.
Value | Position |
---|---|
c | 17 |
a | 16 |
l | 15 |
l | 14 |
space | 13 |
m | 12 |
e | 11 |
space | 10 |
d | 9 |
e | 8 |
v | 7 |
space | 6 |
S | 5 |
t | 4 |
e | 3 |
v | 2 |
e | 1 |
Counting from behind, it chops off the first five positions and starts to return from the 6th position up until the 9th position which is our first argument, and chops off everything after the 9th position. Remember we are counting from behind.
Output
Value | Position |
---|---|
d | 9 |
e | 8 |
v | 7 |
space | 6 |
Now this above examples are when we count from behind using 1 as start, next I will show you how to interpret it with the count from 0.
counting from 0
starting our count from index 0.
Syntax
slice(showIndexBefore)
The Breakdown
As specified earlier with our count from 1, when we have a single negative index as our argument, it actually returns those number of positions rather than chopping them off.
When we count behind(right to left) from 0, we show the indexes before the specified index parameter. Take for instance we have -6 as our argument, it returns str[0]
to str[5]
rather than chop them off, let us see some code.
const str=" I heard PHP devs love lambos"
const text = str.slice(-6)
console.log(text)
//'lambos'
The above code returns lambos
which are the values from index 0 to index 5 before index 6 which was specified as our negative index argument.
Value | Index |
---|---|
I | 27 |
space | 26 |
h | 25 |
e | 24 |
a | 23 |
r | 22 |
d | 21 |
space | 20 |
P | 19 |
H | 18 |
P | 17 |
space | 16 |
d | 15 |
e | 14 |
v | 13 |
s | 12 |
space | 11 |
l | 10 |
O | 9 |
v | 8 |
e | 7 |
space | 6 |
l | 5 |
a | 4 |
m | 3 |
b | 2 |
o | 1 |
s | 0 |
Output
Value | Index |
---|---|
l | 5 |
a | 4 |
m | 3 |
b | 2 |
o | 1 |
s | 0 |
With Two Negative Indexes
The slice method with two negative indexes has the same extract philosophy with our slice with positive index arguments except that we count from behind, thereby flipping our two parameters. The first becoming the second and vice versa. In this instance we will start our count from 0.
Syntax
slice(ignoreIndexFrom,ignoreIndexBefore)
The Breakdown
So we count from behind (left to right), performing our operations on the second parameter first, we chop off indexes before it, we return the index which is our argument up to the index before the first argument. We chop off the index from the first argument and all those in front of it(will be back of it in this case since we counting from behind).
const str = "When men were boys,they played"
const text=str.slice(-3,-1)
console.log(text)
//ye
Value | Index |
---|---|
w | 30 |
h | 29 |
e | 28 |
n | 27 |
space | 26 |
m | 25 |
e | 24 |
n | 23 |
Space | 22 |
w | 21 |
e | 20 |
r | 19 |
e | 18 |
space | 17 |
b | 16 |
o | 15 |
y | 14 |
s | 13 |
, | 12 |
Space | 11 |
t | 10 |
h | 9 |
e | 8 |
y | 7 |
space | 6 |
p | 5 |
l | 4 |
a | 3 |
y | 2 |
e | 1 |
d | 0 |
Output
Value | Index |
---|---|
y | 2 |
e | 1 |
Slice with a Combination of Positive and Negative Indexes.
Occasionally we might see that our slice has one negative and one positive index as arguments. I'll be using the count from 0 for my examples, but you can apply the count from 1 philosophy if you like.
Positive First, Negative Second
In this scenario our count takes a kind of convergent pattern, technically we count from left to right for the first argument and right to left(behind) for the second argument.More like ignore indexes for the first argument while counting from left to right and ignore indexes before the second argument while counting from right to left.
syntax
slice (ignoreIndexBefore, ignoreIndexBefore)
const str = "Tech is the future"
const text = str.slice(5,-7)
console.log(text)
// 'is the'
Value | Index |
---|---|
T | 0 |
e | 1 |
c | 2 |
h | 3 |
space | 4 |
i | 5* |
s | |
space | |
t | |
h | |
e | 7* |
space | 6 |
f | 5 |
u | 4 |
t | 3 |
u | 2 |
r | 1 |
e | 0 |
Output
Value | Index |
---|---|
i | 5 |
s | |
space | |
t | |
h | |
e | 7 |
So we basically count from both sides and stop where we find our indexes, we chop off whatever came before them from both sides.
Negative First,Positive Second
In this scenario our first argument is negative and our second is positive, we will count backwards (left to right) in reference to our first argument and forward in reference to our second argument.
Syntax
slice(ignoreIndexFrom, ignoreIndexFrom)
Let us now see an example.
const str = "Tech is the future"
const text = str.slice(-13,7)
console.log(text)
// 'is'
Count back:
Value | Index |
---|---|
T | 17 |
e | 16 |
c | 15 |
h | 14 |
space | 13 * |
i | 12 |
s | 11 |
space | 10 |
t | 9 |
h | 8 |
e | 7 |
space | 6 |
f | 5 |
u | 4 |
t | 3 |
u | 2 |
r | 1 |
e | 0 |
Count front:
Value | index |
---|---|
T | 0 |
e | 1 |
c | 2 |
h | 3 |
space | 4 |
i | 5 |
s | 6 |
space | 7 |
t | 8 |
h | 9 |
e | 10 |
space | 11 |
f | 12 |
u | 13 |
t | 14 |
u | 15 |
r | 16 |
e | 17 |
So we ignore from 13 upwards when counting from behind, and ignore from 7 downwards when counting normally.
Output
Value | Index |
---|---|
i | 5 |
s | 6 |
With Arrays
At this point you should have a good understanding of the slice, so I won't be going in depth like I did with the string slice because the concepts are all the same as long as you know that array indexes are separated by commas. You should be able to apply all you've learnt so far. You only need to know that slice returns a new array by creating a shallow copy of the old array and returning as a new array.
So I'll just post some code below, each showing the different negative index slice scenarios. The positive index is quite straightforward to understand. You can use any of the count methods(from 0 or 1) to practice.
const array=["Steve","kim","Ben","Joe","Dave"]
//one positive one negative index
const newArray=array.slice(2,-1)
console.log(newArray)
//two negative indexes
const anotherArray=array.slice(-2,-1)
console.log(anotherArray)
//one negative,one positive
const newArray2=array.slice(-4,2)
console.log(newArray2)
//one negative
const newArray3=array.slice(-4)
console.log(newArray3)
The Splice Method
The splice is a JavaScript array method, it is not a string method. The splice basically works as a value substitution method on arrays, it could also be used to delete a value outright.
Syntax
array splice(index, howMany)
array.splice(index, howMany, item1, ....., itemN)
The Breakdown
Whenever we have just two arguments index
and howMany
, it means it will be deleting a value.
index
β represents the starting point for the index which we intend to change the value, while howMany
specifies the number of indexes which their value will be changed or removed. item1
is the value that will be substituting the value whose index is specified as first argument. Whenever howMany
is greater than 1, it means we will be changing or deleting more than one value. We maintain our index count from 0.
//delete a value
const array=["rice","meat","fish","shrimps"]
array.splice(1,1)
console.log(array)
//["rice","fish","shrimps"]
The above code starting from index 1 deletes meat
alone and doesn't replace it.
//delete 2 values
const array=["rice","meat","fish","shrimps"]
array.splice(1,2)
console.log(array)
//["rice","shrimps"]
The above code starting from index 1 deletes two values meat
and fish
but doesn't replace them.
const array=["rice","meat","fish","shrimps"]
array.splice(1,1,"gravy")
console.log(array)
//["rice","gravy","fish","shrimps"]
The above code replaces meat
with gravy
.
Differences Between Slice and Splice
Slice is used on arrays and strings, while splice is only used on arrays.
Slice returns a new array by creating a shallow copy of the old array and returning as a new array while splice does not return a new array.
Slice does not modify the array, while splice modifies the array.
References
To know more about the splice
, follow any of the links below.
Top comments (0)