Sometimes I see that it is common to do this on javascript
in order to check if a variable
is not undefined
because it has a value assigned:
if(variable) {
/* not undefined, do something */
}
However, I was asking to myself how can I check if variable
is not undefined
in the following situation:
Live Demo: http://jsfiddle.net/Vp8tN/1/
$(function() {
var person = create('John');
var isMarried = person.isMarried;
console.log('isMarried: ' + isMarried);
if(isMarried) {
console.log('Do something!');
}
});
function create(name) {
var person = {};
person.name = name;
person.isMarried = getRandom();
return person;
};
function getRandom() {
var arr = [true, 'No', undefined];
var rand = arr[Math.floor(Math.random() * arr.length)];
return rand;
};
In this case isMarried
variable can be true
, 'No'
, or undefined
.
So, my questions are...
1) How can I check if isMarried
variable is NOT undefined
because it is ===
true
(equals true) or because it has a value assigned? (this last one happens when isMarried === 'No'
).
2) Is it possible to check this without using an extra if
statement or condition?
3) What's the better approach for checking this?
In both cases described above (at number 1) I got inside the if
statement. Check the output from browser console
:
isMarried: true Do something! isMarried: undefined isMarried: No Do something!
PS. I am using jQuery
just for testing, this question is NOT related to that framework! Thanks.