Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Error from undefined check [duplicate]

Tags:

javascript

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?

like image 212
xplitter Avatar asked Jul 26 '26 03:07

xplitter


1 Answers

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'
like image 58
Magus Avatar answered Jul 27 '26 19:07

Magus