0

I'm a little confused with the syntax here.

window.foo = window.bar || {};

Any ideas? I'm just trying to understand javaScript better. Thanks

Danny Bullis
  • 3,043
  • 2
  • 29
  • 35
  • possible duplicate of [What does "var FOO = FOO || {}" mean in Javascript?](http://stackoverflow.com/questions/6439579/what-does-var-foo-foo-mean-in-javascript) – Josh Lee Aug 24 '11 at 17:27
  • http://stackoverflow.com/questions/3088098/in-javascript-what-does-it-mean-when-there-is-a-logical-operator-in-a-variable-d – Josh Lee Aug 24 '11 at 17:35
  • 1
    Ah. Yeah I checked those out too and they're also very helpful. I suppose not quite understanding the concept makes it hard to understand how to formulate a question. Thanks for the help! Cheers – Danny Bullis Aug 24 '11 at 18:08

1 Answers1

5

If window.bar is null or undefined (also: 0, "", NaN and false) then window.foo will be set to an empty object ({}), otherwise it will be window.bar.

The logical OR operator (||) works as a null coalescing operator in this situation. It's basically shorthand for:

window.foo = (window.bar != null ? window.bar : {});

This post explains the behavior in more detail.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • If window.bar is __falsy__ (which includes but is not limited to null and undefined) then window.foo will be set to an empty object. – Cristian Sanchez Aug 24 '11 at 17:28
  • Why would a developer want to do that, though? Just so it doesn't throw an undefined error? – Netside May 23 '21 at 03:17
  • 1
    @Netside: I think normally you wouldn't have two separate variables here. A normal use case would be `window.foo = window.foo || {}`. This simply prevents redefining `window.foo` in case you ran a script twice, or ensures that it is defined for some other script that might depend on it. – Cᴏʀʏ May 24 '21 at 16:36
  • @Cory I understand. Thank you, also. – Netside Jun 03 '21 at 04:04