DEV Community

Discussion on: 💡 How to check if a variable is undefined in JS

Collapse
 
martinmuzatko profile image
Martin Muzatko

What are the use-cases?
In web applications where we mostly deal with handing data from one instance to another (database -> service -> restapi -> front-end -> render). The chances are, you almost never need type checking.
Is it undefined? Well don't send it in the first place or let the database handle it.

All these checks belong to the data instance where it is coming from. So the database has to do all the checking to make sure you are not giving it NULL when it does not allow it. Or if you use a file with JSON, the author needs to make sure it is valid.

And I can think of plenty cases where implicit boolean tests are just fine and do the job.

Like: rendering a string based on its existence

Say you have a vue/react/angular/whatever app that only renders the

tag if a users address details are available.
Here we don't need to check for typeof user.address !== undefined or user.address !== undefined && user.address !== null && typeof user.address == 'string
It is simply enough to check for a truthy value. so if(user.address) render() is doing the job just fine. By the contract of the data objects given by the rest api, we know that user.address will be either undefined or a string containing the address. The user might fill in a random string, a random number or whatever. It is the backend and frontend validations job to not let invalid values pass into the database, and the database as last resort can still reject it.

As for undefined variables. I never have this problem. I explicitly require or import libraries and I define variables. I avoid race conditions at all times.