Code must be able to respond and react to user input. For example, in a game, if the user has no more lives left, the game should end. In this article, we'll analyze how a conditional operator, or the if
statement, works in JavaScript.
The if
statement implements the execution of certain commands, providing that logical expression (condition) takes the true
value.
The condition in this construction can be of any expression. JavaScript automatically converts its result to a Boolean value by calling the Boolean()
function on it. If the condition is equal to true
, the statement is executed, otherwise, it is not.
Structure of If statements
Syntax:
if (condition)
instruction
Note. The if
keyword must be written in lowercase. Using capital letters (If or IF) will result in a JavaScript error. The if
statement consists of:
the
if
keyword;a condition (expressions in parentheses) that must be true or false (or cast to one of these values);
an instruction to be executed if the condition is true or cast to it.
Example:
if (true)
count = 4;
This example uses true
as the condition. This means that the instruction count = 4
will always be accomplished.
Using
Let's try to increase the value of the variable votes
by 1 if it (or its type) is a number:
if (typeof votes === 'number')
votes++;
If you need to execute several instructions, they must be placed in curly brackets:
if (typeof votes === 'number') {
votes++;
console.log('Number of votes: ' + votes); // Number of votes 2
}
It is recommended to use curly brackets even while using a single statement. This clearly shows what needs to be done in each case and improves the readability of the code.
if (typeof votes === 'number') {
votes++;
}
To execute multiple statements in a condition, it is important to use the block operator {...}
to group those statements. In general, it is always helpful to use block statements, especially in code that includes nested if
statements. Thus, executable instructions can be represented by a single line or a block of code (a group of lines in curly brackets).
Example:
<script>
const a = 10, b = 5;
if (a > b) alert( " the value of a is greater than b "); // one line statement
if (!(a == b)) {
alert( " the value of a is not equal to b " ); // a group of lines
alert( " the value of a is equal to b " );
b = 10;
}
</script>
Converting conditions to true or false
If the expression in the if
statement is not true or false, JavaScript will shift it to one of these values. It performs this action by using the so-called "rule of lies", i.e. any expression is true, except for the following values:
false
;""
or''
(empty string);NaN
(special numeric data type "not a number");0
(number "zero");null
("empty" value);undefined
("undefined" value).
These are sometimes called "falsy" values, since the code under this condition will never be executed.
Example:
if (0) { // 0 is false
...
}
However, under this condition, it will always be executed:
if (1) { // 1 is true
...
}
Do not confuse the primitive Boolean values true
and false
with the truthfulness or falsity of a Boolean object. Any value that is not undefined
, null
, 0
, NaN
, or the empty string (""
), and any object, including a Boolean object that is false, is considered true
in case it is used as a condition. For instance:
const b = new Boolean(false);
if (b) // this condition is true
if…else construction
The else
statement is a part and continuation of the if
statement used to define a block of JavaScript code that will be executed if the given condition returns false
.
Syntax:
if (condition) {
// block of code executed if the condition returns true
} else {
// block of code executed if the condition returns false
}
Subsequently:
The
if
keyword appears before the parentheses.The condition is located inside parentheses (for example "is this value greater than another value?" or "does this value exist?").
Inside the curly brackets
{}
is the code that will be executed only if the condition is true.The
else
keyword means "otherwise".
Practical examples
Example 1
Let's generate a "Good afternoon" greeting line if the time is less than 18:00, otherwise it should be "Good evening":
if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
Note that the else
and the second block of parentheses {}
are optional as without them the following code will work as well:
if (condition) {
code to execute if condition is true
}
some other code
Nevertheless, you should be careful, if the code inside the second curly brackets {} is not controlled by the condition, then this code will always be executed. Finally, sometimes you may come across if ... else
code without curly braces in abbreviated form:
if (condition) code to run if condition is true
else run some other code instead
This is absolutely feasible code, but less readable and due to this it is better to use curly braces, newlines and indentation.
Example 2
To understand the syntax better, let's take a look at a real example. Imagine a mother or a father asking their child for help with household chores. They may say, "If you help me with the shopping, I will give you extra pocket money to spend on the toy you want." In JavaScript, we can represent it in the following way:
let shoppingDone = false;
if (shoppingDone === true) {
let childsAllowance = 10;
} else {
let childsAllowance = 5;
}
In this code, as it is shown above, shoppingDone
will always be false
, which is disappointing for the kid. You have to introduce a mechanism for a parent to set shoppingDone
to true
if a kid child helps with shopping. Thus, we get:
<script>
const checkBox = document.querySelector('input');
const para = document.querySelector('p');
let shoppingDone = false;
checkBox.addEventListener('change', () => {
checkBox.disabled = true;
shoppingDone = true;
updateAllowance();
});
function updateAllowance() {
let childsAllowance;
if (shoppingDone === true) {
childsAllowance = 10;
} else {
childsAllowance = 5;
}
para.textContent = `Child has earned \$${childsAllowance} this week.`;
}
updateAllowance();
</script>
else if
The previous example provides two choices, or outcomes - but what if we need more than two? There is a way to bind additional options/results to the if ... else
that is to use an else if
construction.
Each additional choice requires an extra block to be positioned between if () {...}
and else {...}
. Let's check out the following complex example, which might be part of a simple weather forecast application:
<label for="weather">Select the type of weather today: </label>
<select id="weather">
<option value="">--Make a choice--</option>
<option value="sunny">Sunny</option>
<option value="rainy">Rainy</option>
<option value="snowing">Snowy</option>
<option value="overcast">Cloudy</option>
</select>
<p></p>
const select = document.querySelector ('select');
const para = document.querySelector ('p');
select.addEventListener ('change', setWeather);
function setWeather () {
const choice = select.value;
if (choice === 'sunny') {
para.textContent = 'Its nice and sunny today. Wear shorts! Go to the beach or park and buy some ice cream. ';
} else if (choice === 'rainy') {
para.textContent = It is raining outside; take your raincoat and umbrella and don't stay outdoors for too long. ';
} else if (choice === 'snowing') {
para.textContent = 'It is snowing and freezing outside! It is better to stay at home and drink a cup of hot chocolate or make a snowman. ';
} else if (choice === 'overcast') {
para.textContent = 'No rain, but the sky is gray and gloomy; it could change at any moment, so take a raincoat just in case. ';
} else {
para.textContent = '';
}
Let's elaborate
Here we have an HTML
<select>
element that allows us to select different weather options and a simple paragraph.In JavaScript, we create links to the
<select>
and<p>
elements and add an event handler for the<select>
element so that when the value changes, thesetWeather ()
function is triggered.When the function is activated, we will initially define the value of the
choice
variable, which is equal to the selected value in the<select>
element. We then use the conditional operator to display the text within the paragraph, depending on the value of thechoice
variable. Notice how all conditions are checked in theelse if () {...}
blocks, except for the first one, which uses theif () {...}
block.The last choice, inside the
else {...}
block, is basically a last resort - the code inside it will be activated if none of the conditions are true. In this case, it serves to remove text from the paragraph if nothing is selected, for example, if the user decides to reselect the option "--Make a choice–" which is indicated in the beginning.
Ternary operator
In the case of not very complex conditional structures it is very convenient to use a ternary operator. In case when we need to declare a variable depending on a condition as in the previous example. Sometimes using a ternary operator is a very convenient way to write programs.
(condition) ? value_first : value_second;
The first operand is used as a condition, it is calculated and converted to a true or false value. If the result of the condition is true, the first value is returned and calculated if necessary. If the condition is false, the second value is calculated and returned. For example:
var c = (a<b) ? "B greater than A" : "A greater than B";
The ternary operator can also have several conditions and assignments. However, it can be difficult to read and can lead to errors. Therefore, the ternary operator can both simplify life and make reading, processing and operation of the program more difficult.