-6

This is my code:

var something = false; 
myFunction(something);    
function myFunction(x) {
    x = true;
}

It does not work, the boolean still remains false. What do I have to change so it will work?

Buchy
  • 1
  • 1
  • 2
  • 3
    JavaScript is pass-by-value. You cannot do what you're trying to do in JavaScript, though you can do some similar things. – Pointy May 04 '15 at 18:38
  • JavaScript is pass-by-value so something is `false` and x is `true` – αƞjiβ May 04 '15 at 18:39
  • For example, you could **return** the new value from the function, use a **closure** instead (but that would be quite limiting) or store the values you want to change as **object properties** and pass the object. Nothing is as clear as returning the new value from the function though, IMO. – Felix Kling May 04 '15 at 18:41
  • 1
    @mins *sigh* ... the most-upvoted answer to that question is simply wrong. – Pointy May 04 '15 at 18:46
  • @mins I see your question and I [raise you this one](http://stackoverflow.com/questions/7744611/pass-variables-by-reference-in-javascript/7744623#7744623) :) – Pointy May 04 '15 at 18:47
  • @FelixKling thanks! It's such a frustrating meme :) – Pointy May 04 '15 at 18:51
  • @Pointy: arguments / parameters in JS are passed by a mechanism named [object reference or object sharing](http://dmitrysoshnikov.com/ecmascript/chapter-8-evaluation-strategy/#call-by-sharing). This is neither by-value nor by-reference. – mins May 04 '15 at 20:07
  • @mins sorry, but that's not what the "pass-by-value" / "pass-by-reference" terminology refers to. Those terms were in use long before languages supported things like "objects". Read my answer in the question I linked, and read the ECMA-262 spec. JavaScript is **strictly** pass-by-value. – Pointy May 04 '15 at 20:19

3 Answers3

1

You are passing x by value and not reference. Give this a read http://snook.ca/archives/javascript/javascript_pass

hendrikdelarey
  • 452
  • 3
  • 12
0

It sure does, you're setting x to true, but only in that scope.

JazzCat
  • 4,243
  • 1
  • 26
  • 40
0

You are changing the x only in the scope of the function and not the something where it points to. You can do this by returning x and set that to something.

var something = false; 
something = myFunction(something);    
function myFunction(x) {
    x = true;
    return x;
}

console.log(something)

This will give true.

Kenavera
  • 83
  • 1
  • 8
  • Do make your example less confusing, you should change the function to `function myFunction() { return true; }` and the call to `something = myFunction();`, so that it's clear that the variable you pass in has nothing to do with what happens. – Felix Kling May 04 '15 at 18:48