JavaScript Conditionals

An overview of JavaScript conditionals.
On this page

What are conditions

Programming is all about using logic of if and then. No matter what computer language you are using the rules always revolves around if and then. If this happens do that otherwise do something else, and so on

JavaScript is not different from other languages, in fact it is a c-based language and most of its syntax is like c language. But it is not a high level language like C. It has almost same procedure to check the conditions of any statement like the way it is done in c-language.

Programming is not an alien concept, on the contrary from the day we are born till the day we die our brain is going through the process of trial and error. And this process of trial and error result in programming our mind. An infant does not know the danger of hot iron rod unless its mind either learns it through experiencing itself by touching it or by some other means. The learning process in children mind is all based upon if and then logic.

In JavaScript if block is written as shown below

1if (expression) {
2  // if true execute this block
3}

JavaScript provide support for three different forms of if statement.

  1. only if statement.
  2. if with else statement.
  3. And if with else if statement.

Their format is given below.

 1// 1. only if format
 2
 3if (expression) {
 4  // if true execute this block
 5}
 6
 7// 2. if with else format
 8if (expression) {
 9  // if true execute this block
10} else {
11  // if false execute this block
12}
13
14// 3. if with else...if format
15if (expression) {
16  // if true execute this block
17} else if (anotherexpression) {
18  // if true execute this block
19} else {
20  // if the above two are not true this block is executed
21}

The actual testing of any condition happens within the brackets. These pair of brackets ( ) are called parenthesis while these { } are known as curly braces. There is another one which is commonly used when creating an array [ ] is known as square brackets. They always come in pairs and have their special purpose and are not interchangeable. Let’s see the first use of if block.

1var condition = true // condition can either be true or false
2if (condition) {
3  //do something
4  console.log('Hello To Conditionals !')
5}

The code block followed by the if statement is executed only if the expression or a variable places within the parentheses yields to true but in case of being false this code block is never executed. If there are only two possibilities exist then else block can be used comfortably.

1var condition = false
2
3if (condition) {
4  console.log('it is true')
5} else {
6  console.log('it is false')
7}

In above logic there is no need to check the condition being false but it is implied and understood that if it is not true then else block get executed. What if we are dealing with the case of more than two options. One way is to write multiple if blocks as shown below.

1var number
2if (number == 1) {
3} // execute this block}
4if (number == 2) {
5} // execute this block}
6if (number == 3) {
7} // execute this block}

Using separate if blocks as done above is not only bad logic but also take more cpu ( central processing unit ) cycles. Here we are talking about mutual exclusive case, in which if one possibility is met the other can not be true. Thus above example may generate the same result yet it is not the correct way of writing a programme logic. The above can be written correctly in the following way

 1var number
 2if (number == 1) {
 3  // execute this block
 4} else {
 5  if (number == 2) {
 6    // execute this block
 7  } else {
 8    if (number == 3) {
 9      // execute this one
10    }
11  }
12}

There is nothing wrong in the above code block except that JavaScript language also provide else if block so you do not have to create extra block with else and check if logic inside this block the above is more clearly written as given below.

 1 var number ;
 2 if ( number == 1) {
 3  // execute this block
 4 } else if ( number == 2) {
 5   // execute this block
 6  } else {
 7    // execute this one
 8   }
 9  }
10 }

Nested blocks

The above example uses nested if blocks, but the deeper you go of if blocks more confusing it gets. Our brain can handle the complexity if it comprehends it otherwise it tends to filter it out tagging it as un necessary. In programming most of nested logic can be written alternatively using logic other than if logic . First let’s see this scenario.

 1var number = throwDice()
 2
 3if (number == 1) {
 4  console.log('it is one : ' + number)
 5  // do whatever you want
 6} else if (number == 2) {
 7  //if number is not 1 check for another one
 8  console.log('it is two : ' + number)
 9} else if (number == 3) {
10  //if number is neither 1 nor 2 check another one and so on
11  console.log('it is three : ' + number)
12} else if (number == 4) {
13  console.log('it is four : ' + number)
14} else if (number == 5) {
15  console.log('it is five : ' + number)
16} else {
17  console.log('it is six : ' + number)
18}
19
20function throwDice() {
21  var result = Math.floor(Math.random() * 6 + 1)
22  return result
23}

If the condition being checked has many options, it can be written elegantly using switch block. Let’s first see the general pattern of switch statement followed by the above same example written in using switch statement.

1 switch ( expression ) {
2  case 1:
3  // case 1 code block
4  case 2:
5  //case 2 code block
6  ....
7  default:
8  // default code block
9 }

The purpose of switch statement is to check the value of expression against each provided case where a value is already mentioned. If the match is found, the code is executed and the process is broken by the use of key word break so that it does not fall freely and start checking the other cases.

Here is outer block of switch statement with break keyword

 1 switch ( expression ) {
 2  case A:
 3  //code to execute if the expression yields to A
 4  break;
 5  case B:
 6  // code to execute if the expression yields to B
 7  break;
 8  ......
 9  default :
10  // this code gets executed if the above does not match
11 }

In above code block, the default keyword tells the interpreter to run it only if there is no match found above. But it does not have to be the last one either. Here is the block of code for above example using switch statement.

 1var number = throwDice()
 2switch (number) {
 3  case 1:
 4    console.log('it is one : ' + number)
 5    break
 6  case 2:
 7    console.log('it is two : ' + number)
 8    break
 9  case 3:
10    console.log('it is three : ' + number)
11    break
12  case 4:
13    console.log('it is four : ' + number)
14    break
15  case 5:
16    console.log('it is five : ' + number)
17    break
18  case 6:
19    console.log('it is six : ' + number)
20    break
21  default:
22    console.log(' it is not within the range!')
23}
24
25function throwDice() {
26  var result
27  result = Math.floor(Math.random() * 6 + 1)
28  return result
29}

When learning about switch statement in JavaScript. It should be noted that sometimes you would want to execute a particular code block or statement for more than one case. It is done by writing a default block just after the same cases. For example the code below will execute the default code for case 1 to 3. Then for case 4 and 5 same block of code is used without using default.

 1 var number = throwDice();
 2 switch ( number ){
 3  case 1:   //FIX:
 4  case 2:
 5  case 3:
 6  default :
 7   console.log("it is either one, two or three");
 8   // do something
 9   break;
10  case 4:
11  case 5:
12   console.log("it is either 4 or 5");
13   // do your work
14   break;
15  case 6:
16   console.log("it is definitely six");
17   break:
18 }
19 function throwDice(){
20  var result;
21  result = Math.floor(( Math.random() * 6 ) + 1 );
22  return result;
23 }