Conditional statements in Javascript

December 02, 2018

4 min read

Conditionals

Photo by Jens Lelie on Unsplash

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:

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

You can also have multiple else if statements.

Examples:

  1. Checking if variable is null
let val
if (val) {
  // do some processing
} else {
  // assign value, throw error
}
  1. Checking if a number is positive, negative or zero
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:

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:

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.
  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:

  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:

// 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]}`)
}
  1. While loop

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

Syntax:

while (expression) {
  //do something
}

Example: Incrementing a value until it crosses a limit

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:

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

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.

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.

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.