How to convert a string to a boolean (the right way)
1) You might be tempted to say if(myString)…
…and this would appear to work, for a while. However, it’s really the wrong way to go about this. Observe:
As I mentioned, if(!myString) evaluates to true because that statement only checks if myString exists (e.g. if it’s not undefined or null), not if it evaluates to false.
2) What about creating a boolean object from the string?
Why not try to create a Boolean object from the string? Well, you’d run into an issue similar to the previous problem. Let’s let some example code do the talking, though, have a look:
3) Right, let’s try comparing our string against the string “true”
Really, the correct way we should be going about this is to check if our string equals “true” — if so, then our string is obviously “true”. Otherwise, it must be false. We can do it this way:
Wonderful, it looks like our problem is solved! But, you know something? The above code is kind of messy and a bit long just to check if our string is “true” or not. Let’s see if we can’t clean it up a bit:
Ahh, nice and clean. Just the way I like it! (note: the parentheses are just there for clarity — if you don’t like them or you’re extra extra concerned about line length, removing them won’t cause any errors).