Muzafar Khan
Muzafar Khan

Reputation: 827

Check If statement is true or false by using javascript Truthy and Falsy Value VS '===' operator

I have search a lot and i got multiple way to check if statement is true or false. I found the standard function to check for null, undefined, or blank variables is to use truthy value like.

  if(value) { }

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

I also found that the '===' operator is better to use over '==' operator.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

I need the shorter and save way for doing this. Now i am confuse with these two solution. Do i need to follow the standard way to check the statement is true or false or i need to use the '===' operator.

Upvotes: 2

Views: 4247

Answers (2)

Daksh Gupta
Daksh Gupta

Reputation: 7804

use === for comparing the value as well as type.

use == for comparing by values only

// Example Program
var a = "0";
var b = 0;
console.log(a==b); // true
console.log(a===b); // false

Upvotes: 3

Matthew Herbst
Matthew Herbst

Reputation: 31973

The standard when checking if a value is null or undefined ("blank" in your terminology) is to use x == null. This is short for doing x === null || x === undefined.

You will find that doing x === null doesn't actually work for checking undefined, since

null == undefined // true
null === undefined // false

There is a difference between checking for a "truthy" value and checking for null or undefined. However, both null and undefined are "falsey" values, so if all you want to do is check if your variable exists and is "truthy", then if(x) is fine. Note that certain things you might expect (without experience) to be true/false are not. For example:

'' == true // false
0 == true // false

Then there are some values that aren't "truthy" or "falsey". For example:

NaN == true // false
NaN == false // false

Find a more complete list of weird stuff (and learn more about == vs ===) in this SO post.

<3 JavaScript

Upvotes: 3

Related Questions