Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable === undefined not working

I have the function:

isset = function(obj){
  alert(obj !== undefined);
 }

Then when I do isset(defined_variable) where defined_variable has been declared, the alert box shows true but when I do isset(undefined_variable) where undefined_variable has not been declared, the alert box does not show at all, while I expected the alert box to show false. What am I doing wrong? I have tried using typeof but the results are the same.

like image 285
Supreme Dolphin Avatar asked Jun 20 '26 10:06

Supreme Dolphin


1 Answers

That's because there's a difference between undefined and undeclared.

var foo; // foo is undefined.
// bar is undeclared.

console.log(foo === undefined); // true
try {
  console.log(bar === undefined);
} catch (e) {
  console.error('I had an error!'); // gets invoked.
}

foo = 'something';
console.log(foo === undefined); // false
like image 154
Madara's Ghost Avatar answered Jun 22 '26 00:06

Madara's Ghost