Page 2 of 2
The original programmer of the code had something slightly different in mind to flag being a Boolean. They were working with strings and discovered that if flag was "true" or any non-null string then
evaluated to true. On the other hand if flag was the null string then
evaluated to false. This worked perfectly in this situation as the test was about what to do when the string was null or not.
However our refactoring programmer was unaware of the intent and assumed that flag was simply a Boolean and true or false rather than truthy or falsy.
So why didn't ==true or ===true work if flag was truthy?
For the strict equality operator the result is even simpler. If the two values are of different types then the result is false - and flag is a string and true is a Boolean.
The pattern that you need to follow to make sure that hoisting never causes you any problem is simple:
Don't ever use or rely on truthy and false values.
Always use a Boolean if you need a two state indicator.
This said there are problems even in this approach as there are two distinct ways to create Boolean as:
var b=new Boolean(true);
The bad news is that these two don't always behave in the same way - but that's for another Programmer Puzzle.
For more on this topic:
|Sharpen Your Coding Skills|
Three Warehouses Puzzle
Talking through a problem is often a good way to see what is required for its solution. Reducing it in scale is another good strategy. But as programmers at the end of the day we need to code an algor [ ... ]