I want to know how to if
to check any of these possible states.
I want to know how to if
to check any of these possible states.
Because JavaScript is dynamic, you can try to "coerce" the conversion of these values to boolean
, this will cause all of the items quoted ( null
, undefined
, false
, NaN
, ""
), equals false
.
If you make a comparison of one of the values with == false
, the answer will be true
, however, if you use ===
the answer will be false
. This is because ==
ignores the types and tries to force the conversion to validate the values.
The if
and the negation operator ( !
) have the same behavior as ==
.
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");
}
===
I'm not going to do all the values to not 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");
}
Normally a simple if (variable) is used to determine any of the situations in code, but to detect each situation individually, a summary follows:
null
: if( minhaVariavel === null ) ...
If testing with only ==
is equal to undefined
NaN
: if( isNaN( minhaVariavel ) ) ...
or
minhaVariavel !== minhaVariavel
false
if( minhaVariavel === false ) ...
undefined
: For general use:
if( typeof minhaVariavel == 'undefined' )
If you want to test if the value of an existing variable is undefined:
if( minhaVariavel === undefined ) ...
As reported in the Rodrigo Branas video ( here ), Javascript identifies as false some cases, these being:
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
}
To test what I said, here's the 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");
}
if ( ! variavel ) {
console.log("Variável inválida");
}
Hello, use typeof to check for undefined. For example:
var variavel;
if (typeof variavel === "undefined"){
console.log("sem valor atribuido");
}