Labels

javascript (9) css (3) babel (1) nodejs (1) webpack (1)

Wednesday, November 16, 2016

Javascript If Statement Shortcuts

I'm not sure if this is really a shortcut but it will save you on some typing if you know this little trick.

When I first started out with Javascript I was very explicit while using my if statements. I would do things like:

if(x === true) {
   // do stuff
}

After doing some reading and I found this was completely unnecessary because the parentheses do the conversion for me. In other words, the if statement automatically converts the expression to a boolean. That makes something like this possible:

if(x) { // x is true
   // do stuff
}

There are a few gotchas to know about while doing this, however. For instance, both "true" and "false" evaluate to true. Why? Because they are non-empty strings. The empty string "" would evaluate to false.

Something I see sometimes is this:

if(x != null) {
   // do stuff
}

Again, null will evaluate to false. So in this instance, we are looking at NOT null so if x isn't null, then do stuff. This could be rewritten in this way:

if(x) {
   // do stuff
}

Much simpler, right? If you wanted to do something if it was null you could do this:

if(!x) {
   // do stuff
}

Hopefully this helps you cut down on some keystrokes!

See the Pen VmKgwq by Galastun (@galastun) on CodePen.

No comments:

Post a Comment