Conditional operations in JavaScript
Conditional operations are used to make a part of the code run if a certain condition condition is met.
Disclosure : Certain items and links to products/services are affiliate links, and any purchases you make may result in a commission for us. We are paid to give honest opinions on products and/or services on occasion. You will not be charged any additional fees as a result of this.
The "if" statement
The if
statement tests a condition and executes the enclosed code if the condition is true
and skips the enclosed code if the condition is false
.
Syntax:
if (condition){
enclosed code to run if condition is met.
}
Example:
"use strict";
let defaultUserName = "User1";
let userName = prompt("Enter your username", defaultUserName);
if (userName == defaultUserName){
// this part runs if userName equals defaultUserName
alert("Invalid Username");
}
if (userName.length > 7) {
// this part runs if userName length is greater than 7
alert("Welcome " + userName);
}
The if
statement can be written without braces for the enclosed code if the enclosed code is short. For example, the above example can be written as:
"use strict";
let defaultUserName = "User1";
let userName = prompt("Enter your username", defaultUserName);
if (userName == defaultUserName) alert("Invalid Username");
if (userName.length > 7) alert("Welcome " + userName);
However it is recommended to always wrap your codeblock with braces as in the first example every time you use if
, even if there is only one statement. This improves readability.
The if
statement works by evaluating the condition in parentheses (condition) and converting it to boolean type.
Any condition that is equal to numerical zero returns false. For example:
if (0) {
// The code in here will never run because the 0 evaluates to false
}
if (false) {
// The code in here will never run because the condition is false
}
if (3) {
// The code in here will run because any number other than 0 evaluates to true
}
The "else" clause
The if
statement is sometimes provided an optional else
clause which executes if the condition is false
.
For example:
"use strict";
let defaultNumber = "0";
let number = prompt("Enter number", defaultNumber);
if (number % 2){
alert("The number is odd");
} else {
alert("The number is even");
}
In the above example, the condition is number % 2
which returns the remainder when a number is divided by 2. When an even number is divided by 2, the remainder is 0 (false
) and when an odd number is divided by 2, the remainder is 1 (true
). So basically that’s the best way to check if a number is odd or even.
So if the input number is odd, the condition returns true
and the code in the if
statement is executed. Else if the input number is even, the condition returns false
and the code inside the else
clause is executed.
The "else if" clause
We can even combine the else
and the if
to produce the else if
condition.
For example:
"use strict";
let defaultNumber = "0";
let number = prompt("Enter number", defaultNumber);
if (number == 0){
alert("The number is neither positive nor negative");
} else if (number > 0 ) {
alert("The number is positive");
} else {
alert("The number is negative")
}
You can have as many else if
codeblocks as you want depending on the number of conditions you want to check.
Ternary operator ‘?’
The ternary operator (?
) is a shorter and simpler conditional operator that works like the if
conditional statement. It is represented by a question mark ?
.
Syntax:
condition ? value1 : value2
If the condition is true
, value1 is returned, else value2 is returned.
"use strict";
let defaultNumber = "0";
let number = prompt("Enter number", defaultNumber);
(number % 2) ? alert("Odd number"): alert("Even number");
The example above shows how to check if a number is odd or even using the ternary operator. The ternary operator returns a value and this means that its result can the assigned to a variable:
let oddEven = (number % 2) ? "Odd number" : "Even number" ;
alert(oddEven);
In the above example, if number
is odd, the condition returns true
and the operator assigns the string "Odd number" to variable oddEven
otherwise, "Even number" is assigned.
Chaining the operator is allowed:
Syntax:
condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4 ;
condition1 is first tested. If true
, value1 is returned and if false
, condition2 is tested and so on. The test testing is stopped once a value is returned otherwise all conditions are tested up to the end.
For readability purposes, it can be written as:
condition1 ? value1 :
condition2 ? value2 :
condition3 ? value3 :
value4 ;
Example:
"use strict";
let defaultElement = " ";
let protonNumber = prompt("Enter atomic number", defaultElement);
let chemicalElement = (protonNumber == 1) ? "Hydrogen" :
(protonNumber == 2) ? "Helium" :
(protonNumber == 3) ? "Lithium" :
(protonNumber == 4) ? "Beryllium" :
(protonNumber == 5) ? "Boron" :
(protonNumber == 6) ? "Carbon" :
"Element not found in the system" ;
alert("The element is " + chemicalElement);
The "switch" statement
A switch
statement can be used to replace multiple if
statements. The switch
has one or more case
blocks upon which a value is compared and optionally ends with a default
block.
Syntax
switch(x) {
case 'value1':
// code to executed if x === value1
[break]
case 'value2':
// code to executed if x === value2
[break]
default:
// code to executed if x matches no case
[break]
}
"use strict";
let defaultElement = " ";
let protonNumber = prompt("Enter atomic number", defaultElement);
switch (protonNumber) {
case "1":
alert( 'Hydrogen' );
break;
case "2":
alert( 'Helium' );
break;
case "3":
alert( 'Lithium' );
break;
case "4":
alert( 'Beryllium' );
break;
case "5":
alert( 'Boron' );
break;
case "6":
alert( 'Carbon' );
break;
default:
alert( "Element not found" );
}
Let us explain the above example. A switch
offers strict comparison. Since a number returned by window.prompt()
is a string representation of the input number, we compare it against string cases "1", "2", "3" etc, not against number cases 1, 2, 3.
The switch
will start by comparing protonNumber
to the first case
value that is 1
. If the input was 1, a match occurs, the code block corresponding to case 1 will be executed. Which mean in this case, "hydrogen" will be alerted and then break
will stop the switch execution.
If the input doesn’t match the first case
, the next case
will be tried, and so on until a match is found. Or until a default
is reached.
If a match is found but still there is no break
statement, the switch
execution will continue until a break
is found.
"use strict";
let defaultInput = " ";
let weekDay = prompt("Enter the day of the week", defaultInput);
switch (weekDay) {
case "1":
case "2":
case "3":
case "4":
case "5":
alert( 'Weekday' );
break;
case "6":
case "7":
alert( 'Weekend' );
break;
}
In the example above, lets say the input was 3. The match will occur at case "3"
however the script execution will "fall through" until case "5"
where an alert is shown and then a break
is found. The execution of the switch stops. This means that case "1"
to case "5"
will show the same alert and both case "6"
and case "7"
will also show the same alert.