0

There are lines in Underscore

  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

And I have no idea why obj.slice() was used here to return a obj(array).

If _.isArray(obj) is true, the return becomes obj.slice().

Question

As far as I know, array.slice without parameters does nothing. I think it should be just obj rather than obj.slice().

Is there any reason obj.slice() was used in this line?

1 Answer 1

4

This function should clone something, thus create a new array. If you return obj, there is no cloning at all. From the doc, array.slice():

returns a new array containing the extracted elements.

Calling slice() is a simple way to make a copy of the array. But note that this method only performs a shallow copy (vs a deep copy): with nested arrays (or arrays of objects), the items will keep the same address. Here is a simple example:

var o1 = {"name": "henry"};
var o2 = {"name": "jean"};

var a1 = [o1, o2];
var a2 = a1.slice();

a2[0].name = "modified";

console.log(a1[0].name); // --> "modified"
console.log(a1[0] === a2[0], a1[0] === o1); // --> true
Sign up to request clarification or add additional context in comments.

2 Comments

You are right. I added this detail in my answer, which might be useful.
I think there's no use of shallow copy. I think the result is almost same with using obj rather than obj.slice(). Is there any possible reason to copy obj shallow?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.