3

I am confused with this code that I found in the Google Maps API:

window.google = window.google || {};
google.maps = google.maps || {};

And other code that I saw in a book:

var QQ = QQ || {};

What does it mean?

Why should we print that code at beginning of the JavaScript file?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3165083
  • 91
  • 1
  • 1
  • 2

3 Answers3

6

This means that if window.google doesn't have value (undefined, null) then use {}.

It is a way of assigning a default value to a variable in JavaScript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
4
window.google = window.google || {};

Means if window.google is not set it creates a new object.

Praind
  • 1,551
  • 1
  • 12
  • 25
1

It initializes the object if the object is not initialized.

After creating the object, you have to init it because the results can be unpredictable without init... Without init, the value is undefined (not 0, not null, undefined).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
clement
  • 4,204
  • 10
  • 65
  • 133