true != true in JavaScript ? WHAT THE H*&#?

Started by
2 comments, last by Awoken 7 years, 2 months ago

So this is was my issue, I had an if statement


console.log( a );
if( a ){
   console.log('made it here');
}
console.log( a );

and a was being assigned by dat.GUI, you had a drop down menu and it would assign either true of false to a.

my console output would read

true

true

And I'm scratching my head cursing the computer for never getting me to 'made it here'

then I test a before dat.GUI gets ahold of it and it spits out

true

Now I'm color blind and seeing the difference between the two was only achieved once I happened to be looking at the screen from the right angle. Then I realised that dat.GUI wasn't setting it to true but rather 'true'. :angry:

Advertisement

if('true') console.log('made it here');

Seems to work for me? Or am I missing something? Quick google stackoverflow result on evaluating strings seems to confirm. At least it's boolean now :P.

I think what he wrote about was the problem with JavaScript's concepts of objects coupled with JavaScript's rules about "truthyness"

The language has objects, but if you're in a C++ background everything is actually a map. In this case it appears he stored a string value of 'true', but was expecting it was set as a binary value of true.

Conversion rules for non-Boolean items trigger some often-unexpected rules, often called being "truthy" and "falsy". They lead to annoying problems like the one above. It looks like one thing, it has a string value of one thing, but it may have other properties that aren't immediately visible. The string representation is not all of the object, and the truthy conversion may not match what is expected.

That is one of many reasons I dislike JavaScript.

if('true') console.log('made it here');

Seems to work for me? Or am I missing something? Quick google stackoverflow result on evaluating strings seems to confirm. At least it's boolean now :P.

Yeah, you're absolutely right. this was a while back that I encountered this, but the most frustrating yet for me. I think the problem was I was trying to get the value to false, but instead it was setting it to 'false' and if you if( 'false') it still logs it as true. I just had the boolean values reversed.

This topic is closed to new replies.

Advertisement