How to check if a variable is undefined or null in JavaScript?

I’m trying to check if a variable is undefined or null in my code. Here’s an example:

var EmpName = $("div#esd-names div#name").attr('class');
if (EmpName == 'undefined') {
  // DO SOMETHING
};

But when I run this, the JavaScript interpreter halts execution. How can I correctly JavaScript check if null or undefined to avoid this issue?

Ah, great question! If you’re just looking for a quick way to check if a variable is either null or undefined, I recommend using the loose equality check (== null). It’s one of my personal favorites because it’s short and does the job in one go. The comparison works because null == undefined returns true, and you won’t accidentally match falsey values like an empty string ('') or 0.

So you could write it like this:

if (EmpName == null) {
  console.log("EmpName is either null or undefined.");
}

This is a nice, concise way to perform a javascript check if null without complicating things too much.

Nice start, Emma! Now, if you’re after something a little more explicit—maybe because you’re debugging or just want clear control over the checks—I’d suggest using typeof along with a null check. It’s super reliable and gives you more precision. You can clearly differentiate between undefined and null, and it’s pretty easy to follow.

For example:

if (typeof EmpName === 'undefined' || EmpName === null) {
  console.log("EmpName is null or undefined.");
}

This way, you’re handling both cases distinctly, and if you’re validating external data or debugging tricky edge cases, it works like a charm! This is a more detailed approach to javascript check if null and gives you more clarity.

Exactly, Priyanka! And if you’re working with modern JavaScript (especially with ES2020+ features), you can take advantage of optional chaining to make your code even more resilient. This is particularly handy when you’re dealing with deeply nested data structures, and you want to avoid any runtime errors when checking properties.

For instance:

if (EmpName?.length == null) {
  console.log("EmpName is missing or empty.");
}

With optional chaining, the ?. ensures that you don’t try to access .length if EmpName is null or undefined. This prevents errors without having to explicitly check for null or undefined. It’s a modern, cleaner approach to handle cases where a javascript check if null might pop up, especially in large, complex objects.