The most popular way of handling conditional logic is with the
if statement. It is universal, flexible, and easy to understand. By evaluating a condition, it allows your script to either execute or omit part of the code.
if can be extended by adding optional
else if for an additional condition with the different outcome or optional
else for all scenarios not caught by above conditions.
if statement is even more powerful if you enhance your conditions with the ORs (
||), ANDs (
&&) and brackets:
You can use boolean values of variables/methods/functions to omit the operator in your condition and make the code more readable.
Bang symbol (
!) can be used to flip the value of a boolean:
Bang not only functions as a NOT operator but also changes truthy and falsy values into an (opposite) boolean.
0, empty string
All other possible values are considered truthy.
This is very useful, as it allows you to leverage boolean evaluation on truthy values:
To make it clear - above code is very "dirty" and can be written much better (for example without
else if by applying default value on variable initialization). You will find an example of how to write it better later.
You Should Know
You can level up the use of this feature by leveraging double bang
!! to convert truthy/falsy value into an (appropriate) boolean.
For simple, one-line
if statements, there is also a one-line shorthand:
You could probably use simple
if statements for the whole logic of your code. But you shouldn't. There are some interesting and useful options worth checking out.
If a simple
if statement has only two possible outcomes depending on a condition, ternary is more straightforward and readable alternative. Based on previous example, instead of:
we can use a clean ternary:
Instead of 6 lines of code, we have 1. Awesome! But how does it work? The ternary structure looks like this:
variable = condition ? valueIfTrue : valueIfFalse;. So in the example above, if the
customer.firstName is not empty (is truthy), it will be pushed as the value of
helloPersonalization. If it is empty, the default value will be assigned instead.
You Should Know
The ternary has more uses not than just the standard
if statement. It is awesome text customization with interpolation:
Ternaries are not limited to variables and strings. They can also run functions:
We already covered using OR
|| + AND
&& operators. But by using them correctly, you can optimize the speed of your scripts greatly.
OR evaluates to
true if at least one value is equal to
If the left side of the OR evaluates to
true, we know for sure that the whole statement is
Thanks to it, if we want to use an OR statement and we suspect that one side is much faster than the other, we should use it on the left side.
Left side in the above example is a straightforward and quick check, as all parts of the condition are already within the script. The right side, however, might take seconds to get the data from other system and calculate the value. If the
lastPurchaseDate is before our threshold, we don't have to waste time and API calls. A win for us, and a win for the customer waiting for the script to finish.
Similar logic can be applied to AND operator.
&& evaluates to
true only if both sides are
true. If we have a more straightforward condition or we suspect it might frequently evaluate to
In the above example, we are doing multiple tests ordered from the easiest to the hardest. Thanks to it, if the login is not in the correct format for an email address, we won't have even to check the password or query our encrypted database with a hashed version of the password.
You Should Know
Using shortcircuit is a quite popular pattern, especially for managing user interface components:
Sometimes you have many options for a single condition. You could write it with a simple
if, but the
switch might be much more readable than a long list of
else if statements with nearly identical conditions.
Some things to remember when working with a
- If multiple cases fulfil the condition, a
switchwill execute the first from the top.
- You can assign multiple cases to the same code block:
- Use either
breakstatement to end each case or use the
returnstatement if in function. Otherwise, the switch will also execute all below cases until it encounters one of the above keywords (or hits the last scenario). Of course, there might be some edge scenarios where you want this exact behaviour to happen.
- Always use
defaultstatement, even if you believe it will never be triggered (not required, but best practice). Use it to handle the scenario you haven't considered.
- Cases in a
switchare using strict comparison (
===) for evaluation, so the provided value must match the case not only by value but also by type. A string value of
'0'won't trigger an integer
You Should Know
By default, the switch statement is a single block for the scope. If you, however, want to declare variables of the same name in different cases, you can do it by adding parentheses: