Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to negate bool inside function in JS? [duplicate]

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?

like image 331
adam Avatar asked Dec 14 '13 22:12

adam


3 Answers

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);
like image 58
robbmj Avatar answered Oct 23 '22 19:10

robbmj


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);
like image 39
Adassko Avatar answered Oct 23 '22 19:10

Adassko


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

var test = true;

function changeThisBoolPlease(asd){
    return !asd;
}

alert(test);
test = changeThisBoolPlease(test);
alert(test);
like image 1
crad Avatar answered Oct 23 '22 21:10

crad