If null, Nan, false and Undefined in Javascript

Asked

Viewed 4,503 times

10

I want to know how to make one if to verify any of these possible states.

6 answers

8

Usually a simple if(variable) is used to determine any of the situations in code, but to detect each situation individually follows a summary:

Testing if it is null:

if( minhaVariavel === null ) ...

test only with == amounts to undefined


Testing if it is NaN:

if( isNaN( minhaVariavel ) ) ...

or

minhaVariavel !== minhaVariavel 


Testing if it is false

if( minhaVariavel === false ) ...


Testing if it is undefined:

For general use:

if( typeof minhaVariavel == 'undefined' )

if you want to test whether the value of an existing variable is undefined:

if( minhaVariavel === undefined ) ...

8


Since Javascript is dynamic, you can try to "coerce" the conversion of these values to boolean, this will make all the items cited (null, undefined, false, NaN, ""), equal to false.

If you compare one of the values with == false, the answer will be true, however, if you use === the answer will be false. This is because the == disregards types and tries to force conversion to validate values.

The if and the denial operator (!) have the same behaviour as ==.

Example with if:

var v1 = null;
var v2 = undefined;
var v3 = NaN;
var v4 = 0;
var v5 = false; // Não precisava dessa, né? :p
var v6 = "";

valida(v1);
valida(v2);
valida(v3);
valida(v4);
valida(v5);
valida(v6);

function valida(variavel){
  if(variavel)
    console.log("true");
  else
    console.log("false");
}

Example with ===

I won’t do it with all the values so it doesn’t get too long.

var v1 = "";

valida(v1);

function valida(variavel){
  if(variavel == false)
    console.log("true");
  else
    console.log("false");
  
  if(variavel === false)
    console.log("true");
  else
    console.log("false");
}  

1

  • IIIIM, I will correct!! Thank you for the remark kkk

1

Explanation

As reported in the video of Rodrigo Branas (here), Javascript identifies as false some cases, being they:

  • 0;
  • Nan;
  • ""(empty string);
  • false;
  • null;
  • Undefined.

That is, if I just wanted to check if a variable contains a value, without being afraid of it being null or Undefined, I should just do:

if(variavel) {
  //Seu código
}

Extra

To test this, follow code snippet:

var a = 0;
var b = false;
var c = "";
var d = "abc" * 2;
var e = null;
var f;

if(!a) {
  alert("A false");
}

if(!b) {
  alert("B false");
}

if(!c) {
  alert("C false");
}

if(!d) {
  alert("D false");
}

if(!e) {
  alert("E false");
}

if(!f) {
  alert("F false");
}

-1

Hello, use typeof to check Undefined. For example:

var variavel; 

if (typeof variavel === "undefined"){
  console.log("sem valor atribuido");
}

-1

if ( ! variavel ) {
    console.log("Variável inválida");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.