In JavaScript, mistaking slice for splice (or vice versa) is a common mistake among rookies and even experts. These two functions, although they have similar names, are doing two completely different things. In practice, such a confusion can be avoided by choosing an API that telegraphs the const-correctness of the function.

Array’s slice (ECMAScript 5.1 Specification Section is quite similar to String’s slice. According to the specification, slice needs to accept two arguments, start and end. It will return a new array containing the elements from the given start index up the one right before the specified end index. It’s not very difficult to understand what slice does:

'abc'.slice(1,2)           // "b"
[14, 3, 77].slice(1, 2)    //  [3]

An important aspect of slice is that it does not change the array which invokes it. The following code fragment illustrates the behavior. As you can see, x keeps its elements and y gets the sliced version thereof.

var x = [14, 3, 77];
var y = x.slice(1, 2);
console.log(x);          // [14, 3, 77]
console.log(y);          // [3]

Although splice (Section also takes two arguments (at minimum), the meaning is very different:

[14, 3, 77].slice(1, 2)     //  [3]
[14, 3, 77].splice(1, 2)    //  [3, 77]

On top of that, splice also mutates the array that calls it. This is not supposed to be a surprise, after all the name splice implies it.

var x = [14, 3, 77]
var y = x.splice(1, 2)
console.log(x)           // [14]
console.log(y)           // [3, 77]

When you build your own module, it is important to choose an API which minimizes this slice vs splice confusion. Ideally, the user of your module should not always read the documentation to figure out which one they really want. What kind of naming convention shall we follow?

A convention I’m familiar with (from my past time involvement with Qt) is by choosing the right form of the verb: present to indicate a possibly modifying action and past participle to return a new version without mutating the object. If possible, provide a pair of those methods. The following example illustrates the concept.

var p = new Point(100, 75);
p.translate(25, 25);
console.log(p);       // { x: 125, y: 100 }
var q = new Point(200, 100);
var s = q.translated(10, 50);
console.log(q);       // { x: 200, y: 100 }
console.log(s);       // { x: 210, y: 150 }

Note the difference between translate() that moves the point (in 2-D Cartesian coordinate system) and translated() which only creates a translated version. The point object p changed because it calls translate. Meanwhile, the object q stays the same since translated() does not modify it and it only returns a fresh copy as the new object s.

If this convention is used consistently throughout your application, that kind of confusion will be massively reduced. And one day, you can let your users sing I Can See Clearly Now happily!

  • http://www.ExposingTheAgenda.com/ Rob

    You have made excellent points here and have done so very clearly. If you consider peer review, looks clean and correct. ship it! Your style of writing would make a refreshing book. Consider it, please :)

    • http://ariya.ofilabs.com/ Ariya Hidayat

      Thanks! Perhaps someday when the opportunity presents itself, there will be a book :)

  • Jeremy

    Beautiful explanation. I’ve actually had my bout with slice and splice yesterday

    • http://ariya.ofilabs.com/ Ariya Hidayat

      Glad to know it’s useful.

  • myshonook

    By the way, there’s an easy way to remember the difference, if use the simple mnemonic rule: s_P_lice, where “P” means “Pieces”.
    Thanks for very useful and interesting post!

    P.S. Very good point “don’t code today what you can’t debug tomorrow” — “I wish I knew that yesterday…” ;)

  • http://canvast.lofter.com/ 涛涛 冯

    I made a fiddle for this article, maybe someone need. here is the link:http://jsfiddle.net/canvast/2NSMd/

  • Laszlo Heredy

    Thought this might help. Using a list of three objects isn’t the best way to unambiguously explain behaviour of functions with two arguments =)
    > x = [0,1,2,3,4,5,6,7,8,9]
    [ 0,
    9 ]
    > y = x.splice(1,4)
    [ 1, 2, 3, 4 ]
    > x
    [ 0,
    9 ]
    > y
    [ 1, 2, 3, 4 ]

  • http://www.darrentorpey.com Darren Torpey

    Thanks, Ariya! This is the best — shortest and most clear — explanation of this I’ve seen. I love the advice about API design, too. We don’t talk about that enough! Short and sweet.

    I just shared this article with my whole dev team.

    • http://ariya.ofilabs.com/ Ariya Hidayat

      Good to know that it’s useful!

  • Aliaksei Chapyzhenka

    API naming can be very stressful. I like the idea about past/present forms of verbs.

  • Mareo Lancellotti

    For completeness, I think you should have included an explanation of the arguments that `splice` takes in:

    The first argument is the *start* of what you are cutting out, and the second argument is the *length* of what you are cutting out.

    For example, var array = [‘b’, ‘r’, ‘o’, ‘c’ ,’c’, ‘o’, ‘l’, ‘i’]; var piece = array.splice(5,2); will result in array === [‘b’, ‘r’, ‘o’, ‘c’ ,’c’, ‘i’] and piece === [‘o’, ‘l’].