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?

Bluefire
  • 13,519
  • 24
  • 74
  • 118

2 Answers2

0

Look at this for a full description

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

Community
  • 1
  • 1
Luca Rasconi
  • 1,085
  • 11
  • 30
-1

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

murli2308
  • 2,976
  • 4
  • 26
  • 47
  • Sorry, but this answer is wrong. Javascript doesn't have "pass by reference" (like in C++ or PHP). – georg Nov 19 '14 at 09:34
  • Objects are passed by reference only in javascript and I am sure about it. I made a simple fiddle for it. http://jsfiddle.net/murli2308/npag0fj4/ – murli2308 Nov 19 '14 at 09:49
  • 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). – georg Nov 19 '14 at 10:01