1

I just came across a convention that I'd never seen before:

window.theme = window.theme || {};

Spent some time researching it, and I discovered that that's an alternative to declaring global variables with var. Why and when would I ever want to do it that way? Is it simply down to personal preference?

Also: this doesn't relate directly to the question, but the OR operator there is confusing to me as well. I understand it's function: it sets window.theme to an empty object if it doesn't already exist. Is that just there as a safety precaution in case it's been already instantiated elsewhere in the script?

Leland
  • 2,019
  • 17
  • 28

1 Answers1

1

See this answer for window.varName vs var varName on a global level: https://stackoverflow.com/a/12393346/2592585

My personal preference is to avoid globals, because in enterprise applications, they are open to conflicts, other people messing with them, etc. Security also becomes an issue (do you want some erroneous script from god knows where to have access to that var?). They are similar to what public fields are on a class for Java. "Modern" JS development uses dependency injection or persistent services to share data.

The particular syntax you are referring to reads like this in pseudocode: Set window.theme to either itself, or an empty object. The expression evaluates left to right, so if window.varName is defined, JS evaluates it as a 'true' of sorts and ends there, assigning it to itself. If window.varName is undefined, the statement evaluates to false, and the OR will cause window.varName to be assigned to what is on the right, {}

A more explicit view of how it operates would be to write it as a ternary operator: window.varName = (window.varName ? window.varName : {});, but most prefer your snippet for simplicity, and use a ternary operator for one-line assignments with more complex conditions than a simple undefined check.

The syntax you are referring to is a common practice when doing JS namespacing, or attaching properties to an object that you want defined. If it is already there, cool, keep going, otherwise set it to an empty object so you don't get errors.

Community
  • 1
  • 1
ryanlutgen
  • 2,951
  • 1
  • 21
  • 31