0

I was working on a bug in some code that I wrote, and the culprit turned out to be this snippet (simplified for the sake of the question):

var a = [1, 2, 3, 5, 4]; // later... function f(arr) { var sorted = arr.sort(); // other stuff } // later... console.log(a); // logs [1, 2, 3, 4, 5]! 

My question is, why does a stay sorted after the function is done? Surely in JS all variables are passed by value as opposed to reference?

2
  • 1
    i dont see any function call Commented Nov 19, 2014 at 9:09
  • 1
    I believe this answers your question stackoverflow.com/questions/2835070/… Commented Nov 19, 2014 at 9:09

2 Answers 2

0

Look at this for a full description

Is JavaScript a pass-by-reference or pass-by-value language?

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

2 Comments

Sorry, but this should be a comment, not an answer.
You are right but I can't add comments.
-1

Array is an Object. In javascript all Objects are passed by reference.

3 Comments

Sorry, but this answer is wrong. Javascript doesn't have "pass by reference" (like in C++ or PHP).
Objects are passed by reference only in javascript and I am sure about it. I made a simple fiddle for it. jsfiddle.net/murli2308/npag0fj4
This topic has been discussed ad nauseum, please read the answers in the linked thread. In short, js passes everything by value, but this very value is always a reference (=pointer).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.