Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "foo = foo || {};" not work?

Tags:

javascript

I was experimenting around with some javascript in my browser console and and not sure exactly why this doesn't work. The following code in the console and jsfiddle on my attempts throws the error: Uncaught ReferenceError: foo is not defined

foo = foo || {}; 

The way i interpret this is: if foo of the global object (window in this case) doesn't exist, then create it as an empty object.

Alternatively, the code window.foo = window.foo || {}; works as I would expect. Assigning a value beforehand to foo with foo = 'bar' makes the original statement work when running afterwards as well.

like image 369
Chris M Avatar asked Jan 14 '23 12:01

Chris M


1 Answers

You have to check whether foo is defined first:

foo = typeof foo !== 'undefined' ? foo : {};

It may be a little unintuitive, but there is a difference between being undefined and having a value of undefined (which window.foo returns when window doesn't have a foo property).

A better way would be to add the var keyword:

var foo = foo || {};

Which works because JavaScript hoists the variable declaration up to the top of the current scope, declaring foo and giving it a value of undefined:

var foo;

foo = foo || {};
like image 176
Blender Avatar answered Jan 22 '23 03:01

Blender