Blog / Development / javascript

JavaScript 101: Array.slice and Array.splice methods

  • Rating — 5 (6 voices)
  • by Tony on June 04, 2018
  • Read —
    4-5 minutes
array splice and array slice methods

We’ve decided to take a “programming” topic for a change and fill in some blank places in JavaScript development topic Specifically we’ll describe Array Splice and Slice methods, how you can use this stuff, and what the difference between them.

JavaScript arrays are frequently used to store different types of data. For example, images for galleries, banners, temporary user data, etc. Array.slice and array.splice are those two frequently used methods that will be required to access and change data inside those arrays.

Array.slice

First let’s take a look at slice method. It returns a shallow copy of a portion of an array into a new array. To have the ability to take that portion array.slice can work with two arguments (see the Difference #3).

Array.splice

So, the next function we’ll gonna look at is the splice function. It removes existing data element and/or adds a new item to the array. And this method changes the contents of the original arrays.   

Count from Zero

Now, we’ll take a little pause before examining code samples. Always remember that arrays in JavaScript are zero-based. Meaning that JavaScript starts counting data in the array from number 0. E.g. zero fingers, first finger, second finger, etc.

Remember that arrays in JavaScript are zero-based.

Therefore when you write a starting position for Array.slice method you should start counting from zero, or just add one ahead after you’ve made a count.  

JavaScript  Array Splice vs Slice Difference

Difference #1

As you may note the main differences between Array.slice and Array.splice methods are that Slice does not affect the original array. On the other hand, splice method gives the ability to edit initial array.

Array.slice method does not affect the original array.

So if you’d make a couple of slices of the original array it will stay intact. Opposite to the result, you get if you use Array.splice method.

Difference #2

The second difference is that using Splice you can return an item to the original array. The slice method can return selected objects too, but it returns selected items in the array as a new object.

Difference #3

Array.slice can take two arguments. The first one is gonna be your starting index and the second will be your optional end index.

The 1st argument is required. It marks the starting point of ‘splicing’ (please remember about zero-based count).

The 2nd argument is optional. If the second argument is missing, it will take all the element from the starting argument right to the end of the array.

var array=[orange,banana,tomato,potato,onion]

console.log(array.slice(2));
// gives [tomato, potato, onion]

You can also use negative numbers as arguments. This way you’ll select data from the end of the array.

console.log(array.slice(-2));
// gives [potato, onion],

console.log(array);
// gives [orange, banana, tomato, potato, onion], with original array remains intact.

More examples:

var array2=[3,4,5,6,0];
console.log(array2.slice(2,4));
// gives [5, 6]

console.log(array2.slice(-2,4));
// gives [6]

console.log(array2.slice(-3,-1));
// gives [5, 6]

console.log(array2);
// gives [3,4,5,6,0]

Now if you place an argument NaN, it will be treated as 0

var array3=[orange,banana,tomato,potato,onion];
console.log(array3.slice(NaN,NaN));
// gives nothing [ ]

console.log(array3.slice(NaN,4));
// gives [orange,banana,tomato,potato,]

console.log(array3);
// gives [orange,banana,tomato,potato,onion]

One more thing to notice. If you use the arguments that are greater than the array’s length, then it will work with data only from array’s legth.

var array4=[orange,banana,tomato,potato,onion];
console.log(array4.slice(10,11));
// gives [ ]

console.log(array4.slice(11,2));
// gives [ ]

console.log(array4.slice(2,10));
// gives [tomato,potato,onion], until the end of the array as if the second argument is omitted.

console.log(array4);
// gives [orange,banana,tomato,potato,onion]

Difference #4

The last difference is that Array.splice method can take n number of arguments:

  • 1st argument is required. It specifies what position to add/remove items. Use negative values to specify the position from the end of the array.
  • 2nd argument is optional. It indicates the number of items that should be removed. If 2nd argument is set to 0 (zero), the items won’t be removed. If the 2nd argument is omitted or not passed, all item(s) from provided index will be removed.
  • 3rd argument is optional. It indicates the new item(s) that should be added to the array.
var array=[orange,banana,tomato,potato,onion];
console.log(array.splice(2));
// gives [tomato,potato,onion], it returns removed item(s) as a new array object.

console.log(array);
// gives [orange,banana], original array is altered.

var array2=[orange,banana,tomato,potato,onion];
console.log(array2.splice(2,1));
// gives [tomato]

console.log(array2.splice(2,0));
//returns nothing [ ] , because no item(s) was removed.

console.log(array2);
// gives array [orange,banana,potato,onion] without tomato

var array3=[orange,banana,tomato,potato,onion];
console.log(array3.splice(2,1,"Hello","World"));
// gives [tomato]

console.log(array3);
// gives [orange,banana,"Hello","World",potato,onion]

              -5     -4     -3    -2      -1
               |      |      |     |       |
var array4=[orange,banana,tomato,potato,onion];
               |      |      |     |       |
               0      1      2     3       4

console.log(array4.splice(-2,1,"me"));
// gives back [potato]

console.log(array4);
// gives back array with “me” insted of potato [orange,banana,tomato,"me",onion]

If the 1st argument is NaN, it will be treated as if it is 0.

var array5=[orange,banana,tomato,potato,onion];
console.log(array5.splice(NaN,4,"NaN is Treated as 0"));
// gives [orange,banana,tomato,potato,]

console.log(array5);
// gives ["NaN is Treated as 0",onion]

If 2nd argument is less than 0 or equal to NaN, it is treated as if it were 0.

var array6=[orange,banana,tomato,potato,onion];
console.log(array6.splice(2,-5,"Hello"));
// gives nothing [ ]

console.log(array6);
// inserts “Hello” into the array [orange,banana,"Hello",tomato,potato,onion]

console.log(array6.splice(3,NaN,"World"));
// gives nothing [ ]

console.log(array6);
// but inserts “World” [orange,banana,"Hello","World",tomato,potato,onion]

If the 1st argument or the 2nd argument is greater than Array’s length, each of arguments will use the Array’s length only.

var array7=[orange,banana,tomato,potato,onion];
console.log(array7.splice(23,3,"Add This"));
// gives nothing [ ]

console.log(array7);
// adds “Add This” at the end [orange,banana,tomato,potato,onion,"Add This"]

console.log(array7.splice(2,34,"Add This Item"));
// gives [tomato,potato,onion,"Add This"]

console.log(array7);
// gives [orange,banana,"Add This Item"]

Hope this little article helps you with your project. Good luck and contact us if any web development services are needed!

Tony Sol is the business development manager of GBKSOFT, overseeing the production of all writings for both internal blog and external platforms. He is technical-driven person always looking for new benefits of merging business and software.


Leave a comment
Close

Leave a Reply


Similar Blog Articles

Ukrainian developers

Business

Why Choose Ukrainian Company for Development?

Ukraine is the best destination for you to employ any ideas in Web and Mobile software. Thanks to its abundance of highly-skilled engineers, the country has become a leading software provider in Europe. Ukraine software development companies offer a rich list of advantages that can be divided into four groups: location, labor pool, work approach,...

Rating — 4.9 (14 voices)
top programming languages 2018

Development

Top Trending Programming Languages to Learn in 2019

If you need a short answer to the question what programming language will run the show in 2018, there are three of them: Java, JavaScript, and SQL. However, this is the “answer 42”, which takes into account only current demand, popularity in business sector and average wages across the market.

Rating — 5 (9 voices)
Is it relevant to build websites with PHP in 2018?

Development

Is it Still Relevant to Build Websites with PHP in 2019?

The world of the Internet is similar to the universe – there might be an end somewhere, but we can’t see it. Thousands of new websites are launched each and every day and this tendency doesn’t seem to stop. But have you ever wondered how are these sites are made? When it comes to choosing...

Rating — 4.6 (16 voices)

Categories

All articles Business Company News Development Marketing StartUp App Ideas UI and Design

People are talking about

Tell us

About your project

We’ll estimate your project and give first advice within 24 hours!

We use cookies to improve your experience with our site, including analytics and personalization. By continuing to use the service, you agree to our use of cookies as described in the Privacy Policy.

Testimonials

Gireesh, USA
One word...EXCELLENT.
Very well thought out and articulate communication. Clear milestones, deadlines and fast work.Patience. Infinite patience. No shortcuts. Even if the client is being careless (me). The best part...always solving problems with great original ideas, especially with this strange project where we are making up new words every day!
Excellent
Tao
GBKSOFT did a good job to manage the project. They put in a good effort to communicate with us and make it easier for us to communicate with developers. Good Job
Jonathan
More good work from team GBKSOFT. All well executed. The support within GBKSOFT is excellent. Communication is good too, spoken English as well as written. Support
13
App Futura ExtractGood FirmsClutchAwwwards