Just a quick post, inspired by Laura Kalbag’s post, which included this gem:
We shouldn’t be fearful of writing about what we know. Even if you write from the most basic point of view, about something which has been ‘around for ages’, you’ll likely be saying something new to someone.
One: There is no else if
When you write something like this …
1 2 3 4 5 6 7 | |
… then what you’re actually writing is this …
1 2 3 4 5 6 7 8 9 | |
That’s because there is no else if in JavaScript. You know how you can write an if statement without any curly braces?
1
| |
You’re doing the same thing with the else part of the initial if statement when you write else if: you’re skipping the curly braces for the second if block, the one you’re providing to else. There’s nothing wrong with else if per se, but it’s worth knowing about what’s actually happening.
Two: return Means Never Having to Say else
Consider some code like this:
1 2 3 4 5 6 7 8 9 | |
If the number we pass to howBig is less than 10, then our function will return 'small'. As soon as it returns, none of the rest of the function will run – this means we can skip the else part entirely, which means our code could look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
But wait – if the first if statement isn’t true, and the second if statement isn’t true, then we will always return 'big'. That means the third if statement isn’t even required:
1 2 3 4 5 6 7 8 9 10 11 | |
Note: this post was edited to improve a couple of the examples and to fix some typos.