DEV Community

Cover image for Write if statements like a pro with JavaScript
Anjan Shomooder
Anjan Shomooder

Posted on

Write if statements like a pro with JavaScript

In this blog, you will learn how to write if statements like a pro.

I will teach you by giving you examples of what are some wrong ways people write if statements and how to fix them. So, Let's get started.

Unnecessary else Statements:

Bad way:

const getLargestNumber = (num1, num2) => {
    if (num1 > num2) {
        return num1
    } else {
        return num2
    }
}
Enter fullscreen mode Exit fullscreen mode

Why is it bad?

We know that in a function after a return statement, nothing gets run. So, if num1 is bigger then the function will return the num1. The else statement will never run. So, the else statement is unnecessary here and we can immediately return num2.

Good way:

const getLargestNumber = (num1, num2) => {
    if (num1 > num2) {
        return num1
    }

    return num2
}
Enter fullscreen mode Exit fullscreen mode

No type checking:

Let's see the old function.

const getLargestNumber = (num1, num2) => {
    if (num1 > num2) {
        return num1
    }

    return num2
}
Enter fullscreen mode Exit fullscreen mode

The function takes numbers as parameters but what if strings are passed as arguments?

If they are strings, you know what will happen.

Bad way:

const getLargestNumber = (num1, num2) => {
    if (num1 > num2) {
        return num1
    }

    return num2
}
Enter fullscreen mode Exit fullscreen mode

Bad way with ugly type checking:

const getLargestNumber = (num1, num2) => {
    if (typeof num1 === 'number' && typeof num2 === 'number') {
        if (num1 > num2) {
            return num1
        }

        return num2
    } else {
        return false
    }
}
Enter fullscreen mode Exit fullscreen mode

We might have a type checking but it is super ugly.

But we can do better with guard clauses.

With guard clauses simply you can just write if statements much shorter way. We like to write code that is small and readable.

Basically, with guard clauses, we can immediately exit the function or do any task(like variable reassignment).

const getLargestNumber = (num1, num2) => {
    const NUMBER = 'number'

    if (typeof num1 !== NUMBER || typeof num2 !== NUMBER) {
        return false
    }

    if (num1 > num2) {
        return num1
    }

    return num2
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

So, we are just checking if any of them are not numbers, then immediately exit the function. Notice, we are not using any curly braces. Because curly braces are optional. If the indentation is right with the if statement, the next code will not run. Let's refactor the next if statement.

const getLargestNumber = (num1, num2) => {
    const NUMBER = 'number'

    if (typeof num1 !== NUMBER || typeof num2 !== NUMBER) return false

    if (num1 > num2) return num1

    return num2
}
Enter fullscreen mode Exit fullscreen mode

You can see this function is much shorter and readable than before.

Note

Don't put more than 1 statement without curly braces. Your code formatter will format that wrong way. Also, you might end up having beautiful and short buggy code.

let a = 20
let b = 30
let c = 0

// bad
if (a > b)
    c = a
    console.log(c)

// good
if (a > b) {
    c = a
    console.log(c)
}
Enter fullscreen mode Exit fullscreen mode

Double false condition check

This is one of the things that you can do to make your code more not readable.

let tesla = {
    name: 'Nikola Tesla',
    isAlive: false,
}

if (!tesla.isAlive !== false) return true
Enter fullscreen mode Exit fullscreen mode

This is one of the ugliest types of code you will ever see. Don't ever write something like this.

If else statement for 1 statement

Bad way

let a = 0

if (10 > 20) {
    a = 10
} else {
    a = 20
}
Enter fullscreen mode Exit fullscreen mode

We can fix this with the ternary operator. With the Ternary operator, we can write short if statements in one line. This is heavily used in reactjs development.

Good way with ternary.

let a = 0

10 > 20 ? (a = 10) : (a = 20)
Enter fullscreen mode Exit fullscreen mode

You can see this looks much better than before. Before ? we are checking the condition. If true then execute the following statement. Else execute the statement after :.

Better way with ternary.

let a = 10 > 20 ? 10 : 20
Enter fullscreen mode Exit fullscreen mode

Note

Never try to put nested ternary operators.

Very very bad code with a ternary

let a = 10 > 20 ? (50 === 50 ? 50 : 100) : 20
Enter fullscreen mode Exit fullscreen mode
  • Not using truthy or falsy values.

    • Truthy: Values that represent or return true value are called truthy values. For example all numbers except zero, array, object, string except empty.
    • Falsy: Values that represent or return false values are called falsy values. For example 0, empty string, undefined, null
// truthy value
if (1) return true // is same as if (true) return true
if ([]) return true // is same as if (true) return true
if ({}) return true // is same as if (true) return true

// falsy value
if (0) return false // is same as if (false) return false
if (undefined) return false // is same as if (false) return false
if ('') return false // is same as if (false) return false
Enter fullscreen mode Exit fullscreen mode

Ler's see some examples:

  • check if an array is empty:
// Bad way
if (array.length === 0) return false

// Good way
if (!array.length) return false
Enter fullscreen mode Exit fullscreen mode
  • Check if an object is empty or not
// Bad way
if (Object.keys({}).length === 0) return false

// Good way
if (!Object.keys({}).length) return false
Enter fullscreen mode Exit fullscreen mode
  • Check if a string is empty or not
const string = ''
// Bad way
if (string.length === 0) return false

// Good way
if (!string) return false
Enter fullscreen mode Exit fullscreen mode
  • check if array exists or not:
const arr = null

// Bad way
if (typeof arr === 'array') return false

// Good Way
if (!arr) return false
Enter fullscreen mode Exit fullscreen mode
  • ## Not using short circuit evaluation

Short circuit evaluation means doing AND(&&), OR(||) operation.

Sometimes you don't even need an if statement. A short circuit operation would do the work for you.

  • OR
// Add life to the character if the character has died.

const character = {
    life: 0,
}

// bad way
if (character.life === 0) character.life = 100

// Good way
character.life = character.life || 100

// Better way
const { life } = character // Destructuring

character.life = life || 100
Enter fullscreen mode Exit fullscreen mode

In the last example, I have used javascript destructuring. If you want to learn more about destructuring you can check out this video.

Not using switch statement

If you have a specific value and you want to match it with other values, then you should use a switch statement instead of if/else statements. This will make your code way cleaner.

const kingName = 'Anjan'

// Bad way
if (kingName === 'Thomas') {
    // do something
} else if (kingName === 'Jack') {
    // do something
} else if (kingName === 'Anjan') {
    // do something
} else {
    // do something
}

// good way
switch (kingName) {
    case 'Thomas':
    // do something

    case 'Jack':
    // do something

    case 'Anjan':
    // do something

    default:
    // do something
}
Enter fullscreen mode Exit fullscreen mode

So, that's it for today. If you disagree with me or if you have any questions, please let me know in the comment section.

Shameless Plug

I have made a video about how to build a carousel postcard with React, Material-UI, and Swiper.js.
If you are interested you can check the video.

You can also demo the application form here

Screenshot of Insta Carousel

Please like and subscribe to Cules Coding. It motivates me to create more content like this.

If you have any questions, please comment down below.
You can reach out to me on social media as @thatanjan.
Stay safe. Goodbye.

About me

Why do I do what I do?

The Internet has revolutionized our life. I want to make the internet more beautiful and useful.

What do I do?

I ended up being a full-stack software engineer.

What can I do?

I can develop complex full-stack web applications like social media applications or e-commerce sites.

What have I done?

I have developed a social media application called Confession. The goal of this application is to help people overcome their imposter syndrome by sharing our failure stories.
Alt Text

I also love to share my knowledge. So, I run a youtube channel called Cules Coding where I teach people full-stack web development, data structure algorithms, and many more. So, Subscribe to Cules Coding so that you don't miss the cool stuff.

Want to work with me?

I am looking for a team where I can show my ambition and passion and produce great value for them.
Contact me through my email or any social media as @thatanjan. I would be happy to have a touch with you.

Contacts

Blogs you might want to read:

Videos might you might want to watch:





Discussion (0)