Blog / Development / javascript

JavaScript 101: Array.slice and Array.splice methods

  • Rating — 5 (6 voices)
  • by Tony
  • Updated 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

Business

,

Development

Top 5 Reasons to Build a Custom CMS for Your Website

Maintaining your content with WordPress or other website builder can be effective if you don’t plan to expand your business, increase sales, improve services, and, well, grow. But what business doesn’t plan to grow? Certainly not a successful one. Using custom CMS has a variety of benefits that themselves might make your business successful. Don’t...

Rating — 5 (5 voices)
Java vs JavaScript

Development

Java vs JavaScript: What’s the Difference?

This is a ridiculous topic to discuss, but there are numerous questions about JavaScript vs Java flocking around. Anyway, my teacher liked to say that there are no stupid questions, there are stupid answers. So, with the help of the community of developers, I’ll try to give a reasonable answer to this question. Naming The...

Rating — 4 (20 voices)
PHP 7 vs PHP 5

Development

PHP 5.6 vs PHP 7 Performance Comparison

It has been awhile over a year since PHP 7 was released. The advanced version that is meant to replace PHP 5 and PHP 6 (failed one) version. And, well… if you’re going into development and making final research before signing a contract, this question might bother you. So, if you just wondering around and...

Rating — 4.5 (101 voices)

Categories

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

People are talking about

You've got
a project in mind

What's next?

Send us a message with a brief description of your project.
Our expert team will review it and get back to you within one business day with free consultation and to discuss the next steps.

Testimonials

Andy
I think they do great work. I haven’t yet given them something that they were unable to do. Great
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
Aaron
I’ve been using GBK Soft for the past 3 years and they have been great. Communication is unparalleled to other app development companies. I’ve continued to return to them to improve my iOS app countless times and I will continue to do so in the future. I highly recommend this company! Improve
13
App Futura ExtractGood FirmsClutchAwwwards