The beauty of a program is that it can do different things in different situations. One of the most important tools that enable that is the if-else. In fact, this expression allows us to create conditions in our code. In this JavaScript tutorial, we will see how to use if-else in JavaScript.
This tutorial assumes you have a general understanding of JavaScript, particularly about variables and how to use JS inside HTML. If you don’t, you may want to start with this quick-start guide. Or, you can dive in on variables here.
Conditional Programming
You may have heard this term before. Conditional programming means writing code that can react to different conditions. In other words, in some situations it may do something, in some others something else. It can “adapt” its behaviour.
To implement that, we use a simple approach. We ask JavaScript to check if something has happened, or if the application is in a particular state. If it is, then we execute some code. Instead, if it is not we may just skip the code or execute a different piece of code.
All this fancy description is extremely simple with an example. We can transform into code a statement like this:
If the user is logged in, show the button to go to the profile page. Instead, if he isn’t, show the button to the login page.
Now, it is time to translate this into code.
The Condition
Well, you guessed it. The most crucial pillar of conditional programming is, indeed, the condition.
A condition is a particular line of code where we check if something is true. Is it true that the user is logged in? Is it true that we have money in the account? With the condition, we ask these kind of questions in a way that JavaScript can understand.
So, a condition is an expression – which can be pretty complex – but that can always evaluate to true of false. Yes or no. Black or white. Nothing inbetween.
To implement it, we have some operators that we can use.
Condition Operators
Operator | Name | Description |
---|---|---|
== | equals | Check that two values are the same, without checking the type (e.g. 0 will be equal to null and to false ). |
=== | strictly equal | Check that two values are the same, considering the type (e.g. 0 will not be equal to null or to false ). |
!= | not equal | Check that two values are different, not considering the type. |
!== | not strictly equal | Check that two values are different, considering the type. |
> | greater than | The one on the left is greater than the one on the right. |
< | less than | The one on the left is less than the one on the right. |
>= | greater than or equal | Check that the one on the left is greater than the one on the right, or equal to it. |
<= | less than or equal | Check that the one on the left is less than the one on the right, or equal to i.t |
! | not | Negate a condition, reverting its result (e.g. true becomes false ). |
Examples of applying expressions would be the following.
5 === 5; // true
5 === "5"; // false
5 == "5"; // true
5 === 4 + 1; // true
6 - 1 === 4 + 1; // true
0 === null; // false
0 == null; // true
!true; // false
!false; // true;
5 > 1; // true
-1 <= 0; // true
However, comparing static values is pointless. We should use variables instead. With this in mind, we can start to compare variables and assign the result of the comparison to a new variable.
const a = 10;
let b = 5;
let result = a == b;
// false
console.log(result)
However, we can do quite more than that, by combining multiple expressions.
Equality vs. Strict Equality
Always prefer the strict equality operator (===
). This gives you a more predictable performance and avoids many bugs. If you expect something to be a number, why should it be a string with a number inside? Being stricter here will force you to write better code, and you will catch errors quickly.
Joining Multiple Conditions
Sometimes, checking just one thing this not enough. We need to check multiple things at once or do some more complex comparisons. For example, we may want to know if the user is logged in and if it is an admin. Only if both conditions are true we want to execute the code.
In short, we need a way to join conditions. The first thing we have to do is to wrap each of our original conditions in brackets. That’s not strictly needed, but it will help us clarify things. So imagine we have two conditions, one is (a === 5)
and the other is (b === 3)
. We can join them with two operators.
Operator | Name | Description |
---|---|---|
&& | AND | Both condition must be true at the same time for the combined condition to be true. |
|| | OR | At least one of the conditions must be true for the combined condition to be true. |
We can chain multiple conditions together, and even nest them into one another. Nesting is very important for complex operations, to make it clear what is the order to evaluate conditions. When we nest, we need to resolve from the most deeper level of nesting and going outward.
let a = 5;
let b = 3;
(a === 5) && (b === 3); // true
(a === 5) || (b === 3); // true
(a === 5) && (b === 5); // false
(a === 5) || (b === 5); // false
(a === 5) || (b === 4) || 5 != 3 || 5 + 1 == 0; // true
// Nesting
((a === 5) && (b === 4)) || true; // true
((a === 5) && (b === 4)) && true; // false
If-Else in JavaScript
If Syntax
We can start simple. The most simple condition you can check is an “if” statement. With this statement, you check for a condition and if that is true, you execute a code block. If not, you just skip the block and proceed afterward.
The general syntax for an if
is this.
if (CONDITION) {
ACTIONS TO EXECUTE WHEN THE CONDITION IS TRUE
}
Javascript will execute the code within the curly brackets only if the condition is true
. We can translate this into a working-code example pretty quickly.
let a = 5;
if (a === 5) {
console.log("The variable equals 5");
}
If-Else
We can enrich our if
statement by adding an else. As you can imagine by now, the else comes with an additional code block within curly brackets. We are going to execute it if the condition is false.
if (CONDITION) {
CODE TO EXECUTE WHEN TRUE
} else {
CODE TO EXECUTE WHEN FALSE
}
A working example can go like this:
let a = 5;
if (a === 5) {
console.log("The variable equals 5");
} else {
console.log("The variable does not equal 5");
console.log("Sorry!");
}
Remember, use the else
only if you want to put something in the if
statement. Instead, if you just want to execute some code when the condition is false, negate the condition.
let a = 5;
// BAD
if (a === 5) {
} else {
console.log("The variable is not 5");
}
// GOOD
if (a !== 5) {
console.log("The variable is not 5");
}
Else-If
Else-if is an additional construct we can use to fine-tune our conditions. In fact, with if-else we can do something if a condition is true, and something else if it is false. However, often we may want to check additional conditions when the first one is false.
With else-if, we can check additional conditions if the conditions checked so far were not true. We can add as many else-if we want. This is the syntax.
if (FIRST CONDITION) {
CODE TO EXECUTE IF FIRST CONDITION IS TRUE
} else if (SECOND CONDITION) {
CODE TO EXECUTE IF SECOND CONDITION IS TRUE, BUT FIRST IS FALSE
} else if (THIRD CONDITION) {
CODE TO EXECUTE IF THIRD CONDITION IS TRUE, BUT FIRST AND SECOND ARE FALSE
} else {
CODE TO EXECUTE IF ALL CONDITIONS ARE FALSE
}
In this example, we used the else if
construct twice. You can use it as many times you want, but be aware that the order matters. JavaScript will process them top to bottom. So, for example, the following example will cause a problem.
let a = 5;
if (a !== null) {
console.log("Not null");
} else if (a === 5) {
// This code is never triggered, because 5 is not null and will match
// always the first condition. Only one condition can be matched
console.log("5!");
}
One additional remark, you don’t need to put an else
at the end, you can be fine with just if
and else if
.
If-Else Does Not Listen…
If-Else is a sequential statement. As the code runs, JavaScript will execute it to to bottom, and deal with it as it appears. This means it will deal with it just once.
In other words, this construct will not wait for the condition to happen. It will just evaluate the condition once, when you run the code, and that’s it. For example, if you are waiting the user to click on something to show an alert, this will never work.
// Does not work
if (user.clicksOnSomething()) {
alert("You clicked");
}
So, remember that “if” means “if”, not “when”.
JavaScript If-Else for Full Stack Developers
This JavaScript tutorial is part of a full (and free) course to become a Full Stack Developer. As part of that, there are some hands-on exercises that we put in place so that you can actually remember what you learn.
The Problem
As an exercise, we are building the website of a pretend bakery store, and for that we are going to use some JavaScript. However, since our knowledge of JS is limited, we are going to do something simple and that does not add real functionality for the user.
Instead, you will have to create the code that checks a variable and based on its value tells one of the following three messages:
- Number is even
- The value is zero
- Number is odd
A tip, you can use the modulo operator (%
) to check the remainder of a division between two numbers.
You will have to put all the final code in in script.js
. Try do this on your own, because the solution is coming in the very next paragraph. So be sure to try before going on reading.
The Solution
Okay, so here is the solution. The first and most important thing we need to figure out is how to find if a number is even or odd. Interestingly enough, all odd numbers divided by 2 will always have a reminder of 1. Instead, all even numbers divided by 2 will always have a reminder of 0. As such, we can check if that remainder is equal to 0 or not with this condition (num % 2 === 0
).
The next thing we want to figure out is in which order we want to put the conditions. Since 0 is actually an even number, we need to check that before checking if the number is even. Then, if the number is not zero we can check if it is even. And, if not, it must be odd. This is the final result.
let num = 10;
if (num === 0) {
console.log("The value is zero");
} else if (num % 2 === 0) {
console.log("Number is even");
} else {
console.log("Number is odd");
}
You can check all the code of our Full Stack Development course on GitHub at alessandromaggio/full-stack-course. Or, to see the solution of this tutorial, take a look at this commit.
Performance Considerations (A Better Solution)
While the previous solution is correct, it most likely isn’t the best performing one. In case the number is odd, we evaluate two conditions (first if it is zero, then if it is even or odd). Instead, if it is zero, we evaluate just one condition. However, it is most likely that the number is going to be odd than to be zero, so we are forcing us to check more conditions in more cases. This translates into more computational time.
We can optimize that by checking first if the number is odd. In that case, the remainder is going to be one. If it is not, we check if it is a zero, otherwise we go again with check of zero vs. even. In this way, 50% of the numbers (all odd numbers) will run through a single condition. The optimized solution is the one below.
let num = 10;
if (num % 2 === 1) {
console.log("Number is odd");
} else if (num === 0) {
console.log("The value is zero");
} else {
console.log("Number is even");
}
In Conclusion
To wrap it up, If-Else allows you to run some code only on some conditions. With this JavaScript tutorial on this if-else construct, we learned exactly how to put it in practice. You are adding another powerful tool that will allow you to be a real full stack developer.