js. splice returns removed item?

.splice does return the removed item. However, it also manipulates the array internally. This prevents you from chaining anything to .splice; you must do two separate calls:

value = value.split(',');
value.splice(1, 1);
console.log(value.join(','));

If you do value = value.splice(...), value is overridden, and the array is lost!


.splice is in-place, so just remove the value = and it'll modify the array like you'd expect:

> var value = "c, a, b";
> value = value.split(', ');
["c", "a", "b"]
> value.splice(1, 1);
["a"]
> value
["c", "b"]

var a = ["1","2","3"]
a.splice(1,1) && a
a=["1","3"]

If you find splice's return behavior annoying, as many do, and have to use it often enough within one program, you might consider adding one of the following two custom prototype functions to use instead.

There is the popular spliced option, which behaves as you expected splice to behave in your question.

Array.prototype.spliced = function() {
    Array.prototype.splice.apply(this, arguments);
    return this;
}

value = "c, a, b";
value = value.split(',').spliced(1, 1).join(',');
console.log(JSON.stringify(value));

The other option is one that can be used in a variety of situations. It will perform any array function specified using the parameters after it, and will always return the array.

Array.prototype.arrEval = function() {
    var args = Array.prototype.slice.call(arguments);
    Array.prototype[args.shift()].apply(this, args);
    return this;
}

// splice example
value = "c, a, b";
value = value.split(', ').arrEval('splice', 1, 1).join(', ');
console.log(JSON.stringify(value));

// push example
value = value.split(', ').arrEval('push', 'a').join(', ');
console.log(JSON.stringify(value));

// unshift example
value = value.split(', ').arrEval('unshift', 'f', 'e', 'd').reverse().join(', ');
console.log(JSON.stringify(value));

Doing the same thing in one line without a custom function is also possible with inline variable assignment, for the truly bold.

value = "c, a, b"
value = ((arr = value.split(',')).splice(1, 1), arr.join(','))
alert(value);