2

Here the output for a and b is same but in case of slice() we didn't pass any parameter so the output for a, b, and c must be same. So why is the output of c different from a and b here?

<!DOCTYPE html>
        <html>
        <head>
        </head>
        <body>
        <p id="1"></p>
        <p id="2"></p>
        <p id="3"></p>
        <p id="4"></p>
        <script>
        var a=["a","b","c"];
        var b=a;
        var c=a.slice();
        a.push("date");
        document.getElementById("1").innerHTML=a;
        document.getElementById("2").innerHTML=b;
        document.getElementById("3").innerHTML=c;
        document.getElementById("4").innerHTML=a;

        </script>
        </body>
        </html>

Output:

a,b,c,date
a,b,c,date
a,b,c
a,b,c,date
1
  • You re slicing an original array before push new value into the array which is 'date' Commented Jan 3, 2017 at 5:33

3 Answers 3

3

From MDN:

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

So c is a copy of a whereas b is a reference to it. Thus when you modify a, b changes but c does not.

Sign up to request clarification or add additional context in comments.

Comments

0

you are slice your array before pushing a new element. Also slice returns a new array so the reference of "a" array is not impacting your "c" array.

hope this helps...

Comments

0

a.slice() inside the slice function not declare any value .so not perform any action.And a.slice() != a .Because you are declare the c=a.slice() before push into the array. Slice() not change array values.Its will duplicate array value pass to the c array. If you need ah date just push with array of c

var a=["a","b","c"];
        var b=a;
        var c=a.slice();
        a.push("date");
        c.push('date')
        document.getElementById("1").innerHTML=a;
        document.getElementById("2").innerHTML=b;
        document.getElementById("3").innerHTML=c;
        document.getElementById("4").innerHTML=a;
<p id="1"></p>
        <p id="2"></p>
        <p id="3"></p>
        <p id="4"></p>

Comments

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.