I want to determine if a variable is undefined or has the value null.
In the following example, I want the clause corresponding to the true condition to be executed, that is, the message "EmpName is not defined" is printed on the console, however, the clause in "else" is already executed. which prints "EmpName is defined"
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
console.log("EmpName no está definido");
} else {
console.log("EmpName está definido");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="esd-names">
<div id="name"></div>
</div>
var miVariable; //miVariable está definida pero tiene valor nulo.
console.log(miVariable)
What is the right way?
The value
undefined
is not the same as the string'undefined'
. In your example, I would do:O well
Short answer
Instead of
'undefined'
(string) usenull
(global object).Explanation
'undefined'
andnull
they are not the same nor are they of the same type. The first refers to a string and the second is a global object (see null , Mozilla Developers Network article).NOTE: See amandiel 's answer which clarifies the difference between (string) and (reserved word) or undefined (Mozilla Developers Network article).
'undefined'
undefined
Fragment
In the following example it has been replaced
'undefined'
bynull
and the messages to be printed have been adjusted for each case.Another more general way is to replace the comparison (
EmpName == 'undefined'
) with the name of the variable (EmpName
)Since
javascript
there is no equivalent toisset
as in ,php
you must take into account the following:If the value of the variable is
undefined
use:If the value of the variable is
null
use:If the value of the variable is empty:
You can also use:
If you don't know what type of value the variable has, you can get it with:
console.log(variable)
You can try it like this: