What’s the best way to use JavaScript if not null to check if a variable is not null?

I’m trying to decide between these two methods:

  1. if (myVar) {...}
  2. if (myVar !== null) {...}

Which one is the recommended practice?

Hello dear! My recommendation would be to use if (myVar) (checks for truthy values).

This solution is the most general and checks if myVar is a truthy value. It works for any value that is not falsy, including null, undefined, false, 0, NaN, and "". It’s useful if you want to ensure that the value is neither null nor any other falsy value.

javascript

CopyEdit

var myVar = "Hello"; // Can be any value
if (myVar) {
  console.log("myVar is truthy.");
}

But when should you use this? If you’re only concerned with whether a variable has any meaningful value (not null, undefined, false, etc.), this is your way forward.

Thanks!

Hey @sakshikuchroo! What @Rashmihasija suggested is solid and would definitely work — but here’s another useful one for your toolkit: using

typeof myVar === 'object' && myVar !== null

This combo is great when you specifically need to confirm that a value is a non-null object (since typeof null returns 'object', which can trip you up if you don’t check for null separately).

javascript

CopyEdit

var myVar = {}; // Object example
if (typeof myVar === 'object' && myVar !== null) {
  console.log("myVar is a non-null object.");
}

Use Case:- When you want to check if a variable is specifically a non-null object — helpful if you need more control over types (like filtering out null values but allowing objects and arrays).

Hi! I’ve brought one more solution, and this one focuses on precision. It uses

if (myVar !== null) — this checks only for null.

This solution strictly verifies if myVar is not null, while still allowing other falsy values like undefined, 0, false, and empty strings to pass through. It’s a more precise option when you need to specifically rule out null but don’t mind other falsy values.

var myVar = "Hello"; // Can be any value
if (myVar !== null) {
console.log("myVar is not null.");
}

If you want to ensure that the variable is not null and don’t care about other falsy values like undefined, 0, etc. use this!

Thank u!!