DEV Community

Dahye Ji
Dahye Ji

Posted on

JavaScript Basic - Conditional Statement, if, else, else if, Ternary Operator, switch

if

Sometimes, we need to perform different actions based on different conditions.
An if statement checks a condition and will execute a task if that condition evaluates to true.

let answer = prompt('Do you like dog?');
if (answer == 'yes') alert( 'Dogs are the best!' );
Enter fullscreen mode Exit fullscreen mode

In the example above, the condition is a simple equality check (answer == 'yes'), but it can be much more complex.
If we want to execute more than one statement, we have to wrap our code block inside curly braces:

if (answer == 'yes') {
  alert( "Dogs are the best!" );
  alert( "They are so lovely!" );
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to wrap your code block with curly braces { } every time you use an if statement, even if there is only one statement to execute. It improves readability.

if else

if...else statements make binary decisions and execute different code blocks based on a provided condition.

let answer = prompt('Do you like dog?');

if (answer == 'yes') {
  alert('Dogs are the best!');
} else {
  alert('How can you not like dogs :('); // any value except 'yes'
}
Enter fullscreen mode Exit fullscreen mode

else if

Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.
We can add more conditions using else if statements.

let answer = prompt(`Rate how often you go to gym from 5 to 0 \n 5 if you go to gym everyday. 0 if you don't go at all`, '');
// \n is for line break.

if (answer <= 2) {
  alert( 'You need to work out!' );
} else if (answer <= 4 ) {
  alert('You are doing well, Keep it up!');
} else {
  alert('Amazing. You are working out so hard!');
}
Enter fullscreen mode Exit fullscreen mode

Ternary operator (Conditional operator ‘?’)

Sometimes, we need to assign a variable depending on a condition.
The so-called “conditional” or ** “question mark”** operator lets us do that in a shorter and simpler way.
The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

Syntax

let result = condition ? value1 : value2;
Enter fullscreen mode Exit fullscreen mode

The condition is evaluated: if it’s truthy then value1 is returned, otherwisevalue2.

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {
  accessAllowed = true;
} else {
  accessAllowed = false;
}

alert(accessAllowed);
Enter fullscreen mode Exit fullscreen mode

So, the code above can be written like below using ternary operator.
Technically, we can omit the parentheses around age > 18. The question mark operator has a low precedence, so it executes after the comparison >.

let accessAllowed = (age > 18) ? true : false;
// the comparison operator "age > 18" executes first anyway
// (no need to wrap it into parentheses. you can omit it.)
let accessAllowed = age > 18 ? true : false;
Enter fullscreen mode Exit fullscreen mode

Changed above code for **else if** using ternary operator


let answer = prompt(`Rate how often you go to gym from 5 to 0 \n 5 if you go to gym everyday. 0 if you don't go at all`, '');

let message = (answer <= 2) ? alert( 'You need to work out!' ) :
(answer <= 4 ) ? alert('You are doing well, Keep it up!') :
 alert('Amazing. You are working out so hard!');

Enter fullscreen mode Exit fullscreen mode

switch()

A switch statement **can replace multiple if checks**.
It can be used to simplify the process of writing multiple else if statements. The break keyword stops the remaining cases from being checked and executed in a switch statement.
switch has one or more case blocks and an optional default.

Syntax

switch(x) {
  case 'value1':  // if (x === 'value1')
    // do something
    break;

  case 'value2':  // if (x === 'value2')
    // do something
    break;

  default:
    // do something
    break;
}
Enter fullscreen mode Exit fullscreen mode

The value of x is checked for a strict equality to the value from the first case (that is, value1) then to the second (value2) and so on...
If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break (or until the end of switch if there is no break).
If there is no case matched, then the default code will be executed (if it exists).

let a = 2*2;

switch (a) {
  case 3:
    alert( 'Too small' );
    break;
  case 4:
    alert( 'Exactly!' );
    break;
  case 5:
    alert( 'Too big' );
    break;
  default:
    alert( "I don't know such values" );
}
Enter fullscreen mode Exit fullscreen mode

The switch starts to compare a from the first case variant that is 3. The match fails.
Then 4. That’s a match, so the execution starts from case 4 until the nearest break.

If there is no break then the execution continues with the next case without any checks.

// Example without break

let a = 2*2;

switch (a) {
  case 3:
    alert( 'Too small' );
  case 4:
    alert( 'Exactly!' );
  case 5:
    alert( 'Too big' );
  default:
    alert( "I don't know such values" );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)