JavaScript Basic - Conditional Statement, if, else, else if, Ternary Operator, switch
Tags: javascript, conditionalstatement, ternaryoperator, switch
Published: 2021-11-30 14:53:18

#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`**.

```js
let answer = prompt('Do you like dog?');
if (answer == 'yes') alert( 'Dogs are the best!' );
```
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 <u>wrap our code block inside curly braces</u>:
```js
if (answer == 'yes') {
  alert( "Dogs are the best!" );
  alert( "They are so lovely!" );
}
```
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.
```js
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'
}
```

#else if
Sometimes, we’d like to test **several variants of a condition**. The else if clause lets us do that.
We can <u>add more conditions using else if statements</u>.
```js
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!');
}
```

#Ternary operator (Conditional operator ‘?’)
Sometimes, we need to <strong>assign a variable depending on a condition</strong>.
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 **<u>“ternary”</u>**, because the operator has <u>three operands</u>. It is actually the one and only operator in JavaScript which has that many.
###Syntax
```js
let result = condition ? value1 : value2;
```
The condition is evaluated: if it’s **_truthy_** then **`value1`** is returned, **_otherwise_** – **`value2`**.

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

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

alert(accessAllowed);
```
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 >.
```js
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;
```
Changed above code for `**else if**` using ternary operator
```js

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!');

```

#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
```js
switch(x) {
  case 'value1':  // if (x === 'value1')
    // do something
    break;

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

  default:
    // do something
    break;
}
```
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**, <u>until the nearest break</u> (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).
```js
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" );
}
```
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._

**<u>If there is no break then the execution continues with the next case without any checks<u>**.
```js
// 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" );
}
```