Conditional statements in JavaScript
Tags: javascript, web, programming
Published: 2018-12-02 04:29:25

---
title: Conditional statements in JavaScript
published: true
description: In this post, let's take a look at what are conditional statements, different types of conditional statements and their use cases.
tags: js, web, programming
---

![Conditionals](./https://thepracticaldev.s3.amazonaws.com/i/24t9ab0olr35gu98s8dx.jpg)

<p>Photo by Jens Lelie on Unsplash</p>

In this post, let's take a look at what are conditional statements, different types of conditional statements and their use cases.

Conditional statements help you write code that you want to execute only when a certain condition is met.
There are two types of conditional statements.

- Branching: Taking one of the possible options
- Looping: Repeating an action

### Branching

Javascript has three branching statements:

- If else(-if)

  You can use if else expression when you need to take one of the possible paths.

  Syntax:

  ```js
  if (expression) {
    //do something
  } else {
    // do something else
  }
  ```

You can also have multiple else if statements.

Examples:

1. Checking if variable is null

```js
let val
if (val) {
  // do some processing
} else {
  // assign value, throw error
}
```

2. Checking if a number is positive, negative or zero

```js
if (val > 0) {
  console.log('Value is positve.')
} else if (val < 0) {
  console.log('Value is negative.')
} else {
  console.log('Value is zero.')
}
```

- Switch case statement

The Switch statement is similar to if else(if), switch evaluates your condition and matches one of the case statements. If your else-if chain is getting longer and longer you should think about switching to switch case statement. When using switch case statement you have access to another handy keyword, the _default_ keyword. When the expression does not match any of the case statements, the code inside the defualt block will be executed.

Syntax:

```js
switch (expression) {
  case 1: //do something
    break
  case 2:
    break

  default: // What to do when expression does not match any case
}
```

There is a _break_ keyword inside each case statement so that the execution of the switch case statement stops once it finds a match.

Example:

```js
switch (color) {
  case 'red':
    console.log('Stop')
    break
  case 'green':
    console.log('Go')
    break
  case 'yellow':
    console.log('Slow down')
    break
  default:
    console.log('Invalid')
}
```

- Conditonal operator(?:)
  You will love the syntax for this one, it consise and clear.

```js
  expression ? code block 1: code block 2
```

If the value of the expression is true, code block 1 will be executed, otherwise code block 2 will be executed.

### Looping

There are two different types of loops in Javascript:

1. #### For loop

You would use a for loop when you know the number of iterations in advance.

Syntax:

```js
  for(initilize expression, condition, increment expression){
    // awesome stuff
  }
```

There are three important expression in a for loop

- initilize: Initilize loop count variable
- condition: Expression that will be checked before each loop pass.
- increment: Expression that will be executed after each loop pass.

Examples:

```js
// display a message n times
for (let i = 0; i < 5; i++) {
  console.log('Loops are cool!')
}

let arr = [1, 2, 3, 4, 5]
for (let i = 0; i < 5; i++) {
  console.log(`Value at index ${i} is ${arr[i]}`)
}
```

2. While loop

You would use a while loop when you do not know the number of iterations in advance.

Syntax:

```js
while (expression) {
  //do something
}
```

Example:
Incrementing a value until it crosses a limit

```js
while (val < limit) {
  val += val
}
```

There is a variant of while loop, the do while loop. The difference being the syntax and the fact that it will be executed atleast once, as the condtion is checked at the end of the loop.

Syntax:

```js
do {
  //some awesome stuff
} while (expression)
```

### Break and continue

Loops would be incomplete without these keywords. These keywords allow us to control loops in a way.

The break keyword allows us to stop the loop execution. Why would you want this? Well lets take a look at
increment a value code from above

```js
let val = 2
let limit = 50

while (val < limit) {
  val += val
  console.log(val)
}
/*
Output: 
4 
8 
16 
32 
64 // Opss
*/
```

Clearly 64 should not have been in the output, why is it even there?
Well when val was 32, the loop expression was true since 32 < 50. Now to fix this we would need to add a check on the new value that is generated.

```js
let val = 2
let limit = 50
while (val < limit) {
  let temp = val + val
  if (temp > limit) {
    break
  }
  val += val
}
/*
Output: 
4 
8 
16 
32 
*/
```

While break stops all the next passes of the loop, the continue statement just skips the current pass.

Let's write a code that prints non-zero elements from the array.

```js
let arr = [1, 0, 0, 2, 3, 0, 0, 4, 5, 0]
for (let i = 0; i < 10; i++) {
  if (arr[i] == 0) continue
  console.log(arr[i])
}
```

That's it you know know about branching and looping statements. Do experiment with these to get a hang of them, these are the basics that will help you in the long run.

If you like this post, do share it.