I am getting confusing results on the undefinded check.
In my memory and according to multiple answers (1 2 3 4 5), the following code should work.
// bar is not defined
if (bar) console.log("should not execute");
if (!bar) console.log("should execute");
var foo = bar || 'foo'; // should assign 'foo' but is undefined
But on Chrome (Version 63.0.3239) and Firefox Nightly (Version 60.0a1) I get a
Uncaught ReferenceError: bar is not defined
This happens on console and linked scripts without strict mode
// linked-script.js
(function() {
if (bar) console.log("should not execute");
if (!bar) console.log("should execute");
var foo = bar || 'foo';
})();
// index.html
<script type="text/javascript" src="linked-script.js"></script>
What am I missing?
The problem is that bar does not equals to undefined. It is not defined at all. The variable does not exist. The code crash because you are trying to read a non existent variable.
var bar;
// bar is not defined
if (bar) console.log("should not execute");
if (!bar) console.log("should execute");
var foo = bar || 'foo'; // foo is now 'foo'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With