Distinguish 0 & ""

I know, I know that there should be some topics on this topic. But I used the search and did not get an answer that fits my needs. So, let's go:

I want to check one if condition, if the variable has values โ€‹โ€‹like "null" or "undefined" or "or" ", then I want to assign the value of the variable as" N / A "and if the value is zero (0), it should not assign this variable "N / A".

But the problem here is that "" or null == 0 is true,

So please help me solve this problem, Thanks in Advance

+5
source share
4 answers

Is that what you are talking about? "===" is a strict comparison operator that will not change data types.

if (val === undefined || val === null || val === ""){ // do something }else{ // do something else } 
+1
source

Use === to compare in JavaScript,

 // type doesn't match gives false 0 === null; // false 0 === undefined; // false 0 === ''; // false 0 === false; // false 0 === "0"; // false // type matches 0 === 0; // true 
+5
source

In Javascript, null, undefined, "" (empty string), false, 0, NaN are false values. The condition of checking a variable having any of these values โ€‹โ€‹leads to a false one.

In your case, you can simply check if the variable is false or not, and if you need to exclude 0 from this condition, you can add another test of the condition if the variable! == 0.

for example, in the code below they say that โ€œaโ€ is a variable that you need to check against all false values โ€‹โ€‹except 0, and then you can check (a! == 0) && &! a (and not fake) and assign N / A, leave "a" as it is.

line 1: var a = 0; line 2: a = (a! == 0 &! a)? "N / A": a;

I hope the code above can help you.

+1
source

That's what you need? Just one test case should be enough ...

 if ($var !== 0) $var = 'N/A'; 
0
source

All Articles