简体   繁体   中英

What does “|| {}” mean at the start of a JavaScript file

I am looking at some JavaScript files. Some of them have something interesting at the beginning:

var something = something || {};

Where "something" is clearly a kind of varable name. What does this mean and what does it do? In fact, one file has this and nothing else.

This is a common pattern to make sure a variable exists and if it does not, to set it to a known initial value so it can be used later. In particular:

  • If the variable something already has a value that is not falsy, this line leaves the value of the variable unchanged.

  • If this variable something does not have a value, or is falsy, this line sets the value of the variable to {} .

You will see this pattern a lot when adding properties to an object in a script. Let's say you worked for the company Acme and you had a lot of script files to integrate with other people's code. The Acme object would have a bunch of properties and a bunch of functions. In some scripts you might want to add properties to the object. But you can't just say

Acme.TIMEOUT = 300;

at the top of a file because the variable might not exist. But if it does exist, you want to use the existing variable. If it doesn't, you need to create a fresh object first.

So

var Acme = Acme || {};

will guarantee it exists, and then you can use it.

Be careful with this, though. I don't like this pattern because in modern JavaScript (where we use let and const instead of var ), having an undefined variable will cause an error to be thrown. You should say:

window.Acme = window.Acme || {};

if you are in a browser. The reason for this is that it makes clear Acme is a property of the window object. Referencing a non-existent property of an object is harmless, you just get undefined . But referencing a non-existent variable will throw an error in modern JavaScript (or if not, it should).

It's a default value for "something" variable. So if something is not initialized, it will end up containing a blank object (the {}).

in other words something equals (sometging or {}) where undefined evaluates to false so {} is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM