Secret Life of Ifs
May 29, 2020
Nikhil
4 minute read

If statement is one of the conditional statements in JavaScript. But if is not the most commonly used conditional statement, at least not when you are new to JavaScript. That would be the if-else or nested if else statement. As a person who is new to JS, the learning materials or the execrises never teach you the real world use cases of an if statement. It is always a basic explanation with a basic example after which the materials often move to if-else.

This has bothered me because I always wonder about the use of an if statement is in JavaScript. I mean, we always need a else part while writing the if statements right?

So, what are the usecases for an if statement? Here are some.

1. As a minimal version of if-else


function biggest (a, b) {
	
	if (a > b) {
	console.log("A is greater");
	}
	console.log( "B is greater");
}

biggest (5, 6);

// -> B is greater.

The above example is for checking if a > b or not. Here, you don’t need to add an else part to check if a < b. It is known that if a > b is true what to execute and if it is false, what to execute. This is one way to use if statements. But this technically has an else part to execute when the initial condition is not satisfied. So where else can we use if statements?

2. To replace switch statements

You can essentially write if statements instead of writing switch statements. if statements are easier to write and easier to understand compared to switch statements.

Here is a switch statement:


  function howMuchFor(expr) {
    switch (expr) {
      case 'Oranges':
        console.log('Oranges are $0.59 a pound.');
        break;
      case 'Apples':
        console.log('Apples are $0.32 a pound.');
        break;
      case 'Bananas':
        console.log('Bananas are $0.48 a pound.');
        break;
      case 'Cherries':
        console.log('Cherries are $3.00 a pound.');
        break;
      
      case 'Mangoes':
      case 'Papayas':
        console.log('Mangoes and papayas are $2.79 a pound.');
        break;
      
        default:
        console.log('Sorry, we are out of ' + expr + '.');
    
    }
    
    console.log("Is there anything else you'd like?");
  }


howMuchFor('Cherries');

// -> Cherries are $3.00 a pound.
// Is there anything else you'd like?


This can be replaced with if statements like…


function howMuchFor (expr) {
	if (expr === 'Oranges') { console.log( expr + ' are $0.59 a pound.'); }
	if (expr === 'Apples') { console.log( expr + ' are $0.32 a pound.'); }
	if (expr === 'Bananas') { console.log( expr + ' are $0.48 a pound.');}
	if (expr === 'Cherries') { console.log( expr + ' are $3.00 a pound.'); }
	if (expr === 'Mangoes' || 'Papayas') { console.log( expr + ' are $2.79 a pound'); }
}

howMuchFor('Mangoes');

// -> Mangoes are $2.79 a pound.

Which do you think is easier to write and easier to understand? The one with switch or the one with if?

3. Then there is another usecase… validating!

This is something I learnt while doing a side project (R.I.P) and thought was really interesting. This is the reason I wrote this blog post, because I was not sure if all the people who have just started to learn JavaScript knows about this.

The function I wrote in the project was essentially doing some CRUD (Create, Read, Update, Delete) operations. My friend told me to use if statements to validate the user inputs and I was like wow, this is a great usecase for an if statement!

So, let’s see how to validate using if statement…


let infoDB = {
	firstName: 'Bob',
	lastName: '',
	age: 37
}

if(!infoDB.firstName) {console.log( "Please provide a first name to add your complete information.");} 
if(!infoDB.lastName) {console.log("Please provide a last name to add your complete information.");}
if(!infoDB.age) {console.log( "Please provide a first name to add your complete information.");}

console.log(infoDB);

// -> Please provide a last name to add your complete information.
// Final infoDB object -> { firstName: 'Bob', lastName: '', age: 37 }

The way to read the above statement is if NO (for !) first name in myCompleteInfoDB, do something. Or if NO last name in myCompleteInfoDV, do something and if NO age in myCompleteInfoDB, do something. Although this is very simple and somewhat not a very useful program, this shows how you can validate things using an if statement.

That is it! These are some usecases for using if statements in JavaScript. I know this is just a very basic thing for most of the people. But since it was not covered in the learning resources I used, it really felt interesting and fascinating to me to know that we can use an if statement this way!


Found this article interesting or found a mistake/room for improvement? Please DM/Tweet me @unsungNovelty. This is a part of a series of blogs called #initlogs which shares some interesting things I found while learning to code.