As you probably already know, Javascript has the Boolean valuestrue andfalse. But, what’s interesting and important is that you understand the fact thateverything in Javascript has a built-in Boolean value in addition to it’s ‘obvious’ value, and that Boolean value is known as either falsy or truthy. This may sound confusing, but read on and the concept should become clearer.
Here’s a complete list of falsy values in #"2">
Now you’re probably wondering about truthy values. Well,every value that’s not in the list above is a truthy value. Even if we take false and put it in quotes – like this: “false” – then that is still a truthy value.
Suppose we have the following code in an if statement:
if(someString.indexOf('findthis'))...//do something
The code above checks to see if the ‘findthis’ text is somewhere inside of someString, and if it is it returns the index, which is the position inside someString where the substring ‘findthis’ starts. The problem with this code is the fact that the someString string could very well start with ‘findthis’ (the ‘someString’ string could be something like ‘findthisxzyabc’), which would mean that the indexOf check would return a 0 (because 0 is the position for the very first character in the string). And because 0 is a ‘falsy’ value – meaning that it is treated as a boolean false inside the if statement – then the if statement would evaluate to false even though it should be true in this situation because of the fact that the substring ‘findthis’ was actually found inside someString.
So, you should be very careful when writing your if statements – especially when checking properties that have the potential to return a falsy value. In that situation you should be prepared to handle it appropriately.
It’s worth taking some time to go over the different falsy values to test them out and see how they compare to each other.
False, 0, and “” – all falsy values – are considered to be equivalent and can be compared to one another. This is what that would look like:
0 == false //this is true"" == false //this is true0 == "" //this is also true
However, the values undefined and null are considered to not be equivalent to anything except themselves. So, here is what we would have:
(null == false) // false(null == null) // true(undefined == undefined) // true(undefined == null)// true
And the strange thing about NaN is that it is not considered to be equivalent to anything and that includes itself:
NaN == undefined //falseNaN == NaN //false
Would you like to thankProgrammerInterview.com for being a helpful free resource?Then why not tell a friend about us, orsimply add a link to this page from your webpage using the HTML below.
Link to this page:
Please bookmark with social media, your votes are noticed and appreciated: