Dofactory.com
Dofactory.com
Earn income with your JavaScript skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

JavaScript Conditionals

JavaScript conditionals are logical expressions that evaluate to either true or false. Conditionals are used to determine program flow through if statements and switch statements.

JavaScript Tutorial

if statements

The if statement executes a block of code if the conditional expression inside a pair of parentheses evaluates to true. The conditions typically involve comparison of variables for equality or inequality. Here is a simple example:

var person = { age: 33 };

if (person.age >= 18) {
    console.log ("Adult");             // => Adult
    console.log ("Allowed to vote");   // => Allowed to vote  
}

The block of code that executes following the if-statement can be a single statement or multiple statements enclosed by curly braces, {}.


Short Circuiting

#

All the parts of a logical expression might not be evaluated. The expression will be evaluated only until the true- or false-ness of the entire expression can be unambiguously determined.

Say we have an if-statement with two expressions: a <= 7 and b > 10. They are separated by an || (or) operator.

var a = 4;
var b = 5;

if (a <= 7 || b > 10) {   // true
    console.log("yes");         // => yes
}

Since a = 4, the expression (a <= 7) evaluates to a true value. This means that the entire expression will be true, regardless whether b is greater than 10 or not. Evaluating the second expression (b > 10) is not required and so JavaScript will skip that. This is called short-circuiting the expression.

if else statement

The if-statement may contain an optional else clause that specifies an alternative course of action. The else clause is executed if the expression in the if-statement is evaluated to false.

var password = "secret";

if (password.length >= 7) {
    console.log("okay");
} else {
    console.log("Number of characters must be at least 7.");
}

Multiple else if

If you need to test multiple conditions then if…else if…else is what you can use. If the condition associated with the if statement is true, the statements inside the if block are executed. If the condition is false, each else-if statement is evaluated in the order in which they appear. When a true else-if condition is found, the statements inside that else-if block are executed. If no else-if condition is evaluated to true, the statements inside the else block are executed.

var age = 34;

if (age < 13) {
    console.log("child");        // => child
} else if (age < 19) {
    console.log("adolescent");   // => adolescent
} else {
    console.log("adult");        // => adult
}

switch

As an alternative to a large number of if .. else if .. else statements you can use a switch statement which makes your code a bit more concise and readable.

The switch keyword is followed by an expression you wish to evaluate. This expression is referred to as the control variable that controls the flow of program execution. This expression is evaluated and its value is compared to the value following each of the case labels. Once the matching case label is found, the block of code contained inside that case is executed. The last statement in a block of code is almost always a break statement that signals the end of the block.

You can specify a default case which is optional. It is similar to the else clause of an if statement and is executed when none of the cases match. There can only be one 'default' label for a switch statement. Although default is optional, it is recommended that you include it as it handles any unexpected cases. Here is an example:

var account = 3;

switch (account) {
    case 1:
        console.log("Checking account");   // => Checking account
        break;
    case 2:
        console.log("Savings account");    // => Savings account 
        break;
    case 3:
        console.log("Business account");   // => Business account 
        break;
    default:
        console.log("Invalid account code");
        break;
}

Avoid switch fall-through

#

You should end each case with an explicit break statement. If a break is absent, the case 'falls through', meaning that the control will flow sequentially through the next case statement.

var account = 3;

switch (account) {
    case 1:
        console.log("Checking account");   // => Checking account  
        break;
    case 2:
        console.log("Savings account");    // => Savings account 
        break;
    case 3:
        console.log("Business account");   // => Business account (falls through)
    default:
        console.log("Invalid account code");
        break;
}

In the above code, the break is absent in case 3, so control will fall through to the default case, and the output will be both "Business account" and "Invalid account code", which is incorrect.

Forgetting to add a break is a common error and can cause hard to find bugs. JSLint will report a missing break (or return or throw statement) when it detects one. It does so because most fall-throughs are unintentional. If you intentionally implement your logic to use the fall-through approach, document it properly so that others who read your code don't get confused.


Last updated on Sep 30, 2023

Earn income with your JavaScript skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.
Guides