3

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?

xplitter
  • 33
  • 6

1 Answers1

2

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'
Magus
  • 13,609
  • 2
  • 31
  • 47
  • 2
    Strict mode doesn't matter here. It would prevent you declaring an implicit global, but you've never been able to read an undeclared variable. – Quentin Mar 01 '18 at 11:46
  • Fixed the answer. I always work in strict mode and the time convinced me that this "feature" was from the strict mode. – Magus Mar 01 '18 at 11:51