David is a skilled software developer and technical writer with extensive experience in building scalable backend infrastructure for web applications. He is well-versed in backend-focused software development and database administration, with a track record of delivering reliable software solutions.
As a technical writer with over 2 years of experience, David has written various in-depth articles on these topics, sharing his experience, knowledge, and insights with the wider community. He has a passion for keeping up-to-date with the latest trends and best practices in the field and enjoys sharing this knowledge with others.
Sign in to your MakeUseOf accountA conditional statement let you run a block of code based on a specific condition.
The JavaScript language provides various ways of using conditional statements. Many of them are common to other programming languages too. But you should be aware of their individual benefits and how they work in JavaScript.
1. if-else and else-if StatementsAn if-else statement executes one block if its condition is truthy and the other block if it is falsy. An else-if executes the block that matches one of several conditions, or a default block if no conditions match.
A truthy value is a value that JavaScript considers true when it encounters it in a boolean context. A falsy value is a value that JavaScript considers false when it encounters it in a boolean context.
JavaScript considers all values truthy unless they are one of a small number that are falsy. The falsy values are false, 0, -0, 0n, "", null, undefined, and NaN.
Here’s the syntax for an if-else statement:
if (condition) {
// If the condition is a truthy value, this code block will run
} else {
// If the condition is a falsy value, this code block will run
}
In some cases, you might want to check several, related conditions. In those scenarios, you can use an else-if to evaluate the extra conditions.
For example:
if (condition) {
// If the condition is truthy, this code block will run, and code execution
// will stop.
} else if (condition_2) {
// If the first condition is falsy, this code block will run if condition_2
// is truthy
} else if (condition_n) {
// If the previous conditions are both falsy, this code block will run if
// condition_n is truthy
} else {
// If all conditions are falsy, this code block will run
}
Using else-if statements, you can evaluate as many conditions as you want. However, this method quickly becomes unsightly and hard to maintain as the number of conditions increases.
JavaScript provides a cleaner way to evaluate multiple conditions called the switch statement.
2. The Switch StatementThe switch statement evaluates an expression once and tries to match it against one or more possible values. You can provide each potentially matching value after a case keyword.
When the switch statement finds a match, it runs all the statements after it, until it encounters a break statement.
Here’s the syntax for the switch statement:
switch (expression) {
case 'first-case':
// executes code if the expression matches this case
break;
case 'case_2':
// executes code if the expression matches this case
break;
default:
// executes code if the expression doesn't match any case
}
The break statements are an essential part of the switch block because they specify where the code should stop executing. If you miss out a break statement, the code execution will continue and execute all the other code blocks after the first match. This is rarely what you’ll want to happen.
3. The Ternary OperatorJavaScript also lets you abbreviate conditional statements using the ternary operator.
The ternary operator takes three operands:
A condition, followed by a question mark (?). An expression after the question mark, and before a colon (:). This will run if the condition is truthy. An expression after the colon which will run if the condition is falsy.For example:
condition ? console.log('Condition is truthy') : console.log('Condition is falsy');
The statement above effectively means “If ‘condition’ is truthy, log the first message, otherwise log the second message”.
4. Short CircuitingShort-circuiting is a technique that involves the use of the logical operators OR (||) and AND (&&) to evaluate an expression from left to right.
An operation involving the OR operator will short-circuit by returning the first truthy value it encounters. If all the values in the expression are falsy, it short-circuits and returns the last falsy value.
An operation using the AND operator will short-circuit by returning the first falsy statement it encounters. If all the statements in the expression are truthy, it short-circuits and returns the last truthy value.
Here is an example of writing a conditional statement with the OR operator.
app.listen(process.env.PORT || 3000)
This short-circuiting approach to writing conditional statements is popular in Express applications. It reads, “if the PORT environment variable exists, use it; otherwise, use port 3000”.
Here is an example of writing a conditional statement with the AND operator.
foo && console.log('foo is defined')
The code block above means “if foo is defined, call the console.log() function”.
This technique is the shortest way to write a conditional, but it can make code harder to read. You should avoid overusing it, particularly when you’re working as part of a larger team.
The Importance of Conditional StatementsConditional statements are what allow your program to make decisions. Without them, your code will execute in a straight path from start to finish. They are also part of loops. Without them, loops would run infinitely, thus crashing your application.
Close