DEV Community

Cover image for How to avoid undefined error when comparing in JavaScript
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on

3 2

How to avoid undefined error when comparing in JavaScript

Hey there people

One of the most common errors we encounter in JavaScript is the undefined error when trying to compare two values.
Let me give you an example so you understand it better.

Imagine you have an object that you want to check if a property value is equal to another value, what you are going to do is this:

let myObj = {
    firstName: "Adnan",
    lastName: "Babakan",
    age: 19
};

if(myObj.firstName === "Adnan") {
    console.log("Yes it is true!");
}
Enter fullscreen mode Exit fullscreen mode

This is OK and it will work pretty well, but when you have a scenario in which you don't know if the variable you are using is a object or not what will you do?

let myObj = undefined;

if(typeof myObj === 'object') {
    if(myObj.firstName === "Adnan") {
        console.log("Yes it is true!");
    }
}
Enter fullscreen mode Exit fullscreen mode

You'll do a typeof comparison of course and that is totally fine.

There is another thing that can happen which is if you want to add some else statement in order to control the opposite result, which you will end up with a code like below:

let myObj = undefined;

if(typeof myObj === 'object') {
    if(myObj.firstName === "Adnan") {
        console.log("Yes it is true!");
    } else {
        console.log("Nope!");
    }
} else {
    console.log("Not at all!");
}
Enter fullscreen mode Exit fullscreen mode

So this is kinda messed up. Isn't it?
What is my solution? To use try and catch brothers! (Or maybe sisters)

Using those will give you a neater code and a solid one.

let myObj = undefined;

try {
    if(myObj.firstName === "Adnan") {
        console.log("Yes it is true!");
    } else {
        console.log("No");
    }
} catch(err) {
    console.log("No");
}
Enter fullscreen mode Exit fullscreen mode

So what's the point in this you might ask?
I'll give you few reasons for this:

  1. It looks cool XD
  2. It is way better since you now have access to the error which occurred
  3. You have avoided unnecessary condition

Always remember that conditions are OK until you have no other choice. You better try to avoid them as much as possible.

A real life scenario for this to me was when trying to compare an object which I got from Mongoose (an ODM for MongoDB) like below:

import userModel from './models/userModel'

app.post('/api/user', function() {
    userModel.findOne({ username: 'adnanbabakan' }).then(user => {
        let result = false;

        try {
            if(user.age == 19) {
                result = true;
            }
        } catch(err) {}

        res.json({
            result
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

As you might have guessed this an API made with Express and I wanted to check a simple condition.
My code might have looked really messy with those conditions in it so I decided to do it like this and change the result to true only if my condition was true in any matter.

I hope you enjoyed this and let me know if I'm wrong or there are any better ways to accomplish this. I just wanted to share this solution of mine with you.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay