Martin Schmidt
Martin Schmidt

Reputation: 51

How does bool works in javascript

I'm working on that piece of code which doesn't behave as I expected. Especially conditions. In console log I see that objekt.teamA is false, teamA is false, objekt.teamB is true, teamB is true but 1st condition is accepted without any reason.

Could anybody tell me why is that so?

function wsConnect() 
            {
                var objekt = 
                {
                    teamA: document.getElementById('teamA').value,
                    teamB: document.getElementById('teamB').value
                };
                console.log("connect",wsUri);
                ws = new WebSocket(wsUri);
                ws.onmessage = function(msg) 
                {
                    obj = JSON.parse(msg.data);
                    lightsAv = obj.lights;
                    doorsAv = obj.doors;
                    electricAv = obj.electric;
                    teamA = obj.teamA;
                    teamB = obj.teamB;
                    console.log(objekt.teamA + " " + teamA + " " + objekt.teamB + " " + teamB);
                    //objekt.teamA is false, teamA is false, objekt.teamB is true, teamB is true
                    if(objekt.teamA && !teamA)
                    {
                        console.log("1st condition");
                    }
                    if(objekt.teamB && !teamB)
                    {
                        console.log("2nd condition");
                    }
                }
                ws.onopen = function() 
                {
                    document.getElementById('status').innerHTML = "connected";
                    console.log("connected");
                }
                ws.onclose = function() 
                {
                    document.getElementById('status').innerHTML = "not connected";
                    setTimeout(wsConnect,3000);
                }
            }

Thanks a lot.

Upvotes: 0

Views: 73

Answers (2)

Darshit Chokshi
Darshit Chokshi

Reputation: 589

You are checking if the variable has a truthy value or not. By using,

if( value ) { }

This will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

To compare boolean value, you can use -

if(varA === false && varB === true){ }

Upvotes: -1

Quentin
Quentin

Reputation: 943569

Your claim:

objekt.teamA is false, teamA is false

Your code:

var objekt = 
{
    teamA: document.getElementById('teamA').value,
    teamB: document.getElementById('teamB').value
};

The value of objekt.teamA comes from the value property of a form control. This will always be a string.

So it is not false, it is "false".

Strings of non-zero length are truthy.

if ("false") {
    console.log("a true value")
}

You can test for the value explicitly:

var myVar = "false";

if (myVar !== "false") {
   console.log("It is true");
} else {
   console.log("It is false");
}

Upvotes: 4

Related Questions