JavaScript Conditionals

https://www.dofactory.com/javascript/conditionals

JavaScript Conditionals

if statement

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) {    alert ("Adult");             // => Adult    alert ("Allowed to vote");   // => Allowed to vote  }

Run

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    alert("yes");         // => yes}

Run

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. Previous Next

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) {   alert("okay");} else {   alert("Number of characters in your password must be at least 7.");   return false;}

Run

if…else if…else statement

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) {    alert("child");        // => child} else if (age < 19) {    alert("adolescent");   // => adolescent} else {    alert("adult");        // => adult}

Run

switch statement

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:      alert("Checking account");   // => Checking account      break;   case 2:      alert("Savings account");    // => Savings account       break;    case 3 :      alert("Business account");   // => Business account       break;   default:      alert("Invalid account code");      break;}

Run

Avoid switch fall-through

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

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

Run

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. Previous Next

Last updated

Navigation

Lionel

@Copyright 2023