8

I'm writing some script now and I have a problem when trying to negate boolean inside a function. I mean this:

var test = true; function changeThisBoolPlease(asd){ asd=!asd; } alert(test); changeThisBoolPlease(test); alert(test); 

alerts true, then true.

Any ideas? Isn't JS reference perfect?

EDIT:

Ok, this was only a part of my function:

function przesun(kolor, figury, castlings, x1, y1, x2, y2, strona) { kolor = nowaPozycjaKolor(kolor,x1, y1, x2, y2); figury = nowaPozycjaFigur(figury,x1, y1, x2, y2); strona = !strona; } 

Actually I cannot return this value. How to?

6
  • do you want to return strona? if so just return it. and assign the return. Commented Dec 14, 2013 at 22:42
  • please see my answer, I believe it will answer your question Commented Dec 14, 2013 at 22:44
  • The edit doesn't change anything. Changing the value of the arguments to the function just changes the arguments to the function. It has no effect on whatever variables (if any) were used when sending those values to the function. Commented Dec 14, 2013 at 22:44
  • @robbmj: When you answered the question, the OP received a notification. That's sufficient, don't comment saying "see my answer." Commented Dec 14, 2013 at 22:44
  • fair enough, my comment was more to let the OP know that even after their edit the answer does not need to change. Commented Dec 14, 2013 at 22:45

3 Answers 3

5

You are just changing the value of asd in the example in your question.

try this

var test = true; function changeThisBoolPlease(asd){ return !asd; } alert(test); test = changeThisBoolPlease(test); alert(test); 

Alternatively but not recommended, you could do it this way

var test = true; function changeTestBoolPlease(){ test = !test; } alert(test); changeTestBoolPlease(); alert(test); 
Sign up to request clarification or add additional context in comments.

Comments

2

Objects are not passed by reference but by value which is a reference (copy of reference)...

In your example you're not even passing an object but a primitive value type.

If you want a reference, then you need to wrap it in object element like:

var test = { val: true }; function changeThisBoolPlease(asd){ asd.val=!asd.val; } alert(test.val); changeThisBoolPlease(test); alert(test.val); 

2 Comments

"It's not passed by reference but by value which is a reference..." No, the value is a boolean, not a reference.
yes, you are right in this case but I assumed that true was only an example (which it was) and in reality he's passing an object. Edited
1

It's a scoping issue. Just return and set:

var test = true; function changeThisBoolPlease(asd){ return !asd; } alert(test); test = changeThisBoolPlease(test); alert(test); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.