简体   繁体   中英

Javascript literal notation for array of objects

I'm trying to understand some code written in Javascript and I'm stuck rather the syntax.

var connections = {}; // I know '{}' means new Object()
var messages = {};

the objects contains variables path, version etc. but then in the code what do the following lines do?

connections[ path ] = connections[ path ] || [];
messages[ path ] = messages[ path ] || { version: 0, body: ''};

Since connections and messages are objects, the [ and ] does not denote array indices, but is rather the syntax to access members, where a variable is used to find the name of the variable.

var path = 'x'
connections[path] = connections[path] || [];

The above, since path = 'x' is equal to

connections.x = connections.x || [];

It's saying, if the member of the two objects named by the value of path exists, keep it (assign its current value to itself), otherwise ( || is used for coalesce here) create a new empty array, or a new { version: 0, body: '' } , respectively.

Note that the coalesce / logical OR can easily be chained from left to right. You might for instance in some cases want to do something like this:

function createItem(color) {

   // if a color is specified in the arguments, use that
   // otherwise, if a color is specified in the settings object for this instance
   // of the current user control, use that. otherwise, fall back to the global
   // default values. if none of these settings have been defined, use black.

   color = color || instanceSettings.defaultColor 
                 || globalSettings.defaultColor
                 || '#000000';

   ...

}

Basically it initialize the path property if it hasn't been initialized before or it contains null or false or 0.

In other words (or other code):

if (connections[path] === null || connections[path] === undefined || connections[path] === 0 || connections[path] === false) {
    connections[path] = [];
} else {
    connections[path] = connections[path];
}

Same for messages[path] only it initializes it with some object and not empty array.

The key is to understanding the logical OR ( || ) operator. In JavaScript, the expression to the left of the operator is tested first. If it resolves to true, that expression is returned; if it resolves to false, the expression on the right is returned. This is a great way of assigning default values to a variable.

Secondly, connections[path] is not accessing an element of an array. If path resolves to a string, then connections[path] is equivalent to connections.path , it's simply accessing that member of the connections object.

connections[path] = connections[path] || [];

The person writing this code wanted the path member to be, if nothing else, an empty array. This line is essentially checking if connections[path] is truthy . If there is something in that path member, it will be left alone; if not, it will be an empty array.

messages[path] = messages[path] || { version: 0, body: '' };

This functions the same way as the previous line except the default value is an object with two members in it rather than an empty array.

connections[ path ] = connections[ path ] || [];

roughly translates to

connections[ path ] = connections[ path ] != null ? connections[ path] : [];

In this case this is a convenient way to set default value for connections[path] (that is, set value to [] if no value is already set)

In some languages (Ruby, for example) this could be written even shorter

connections[path] ||= []

The || operator means OR so with connections[ path ] = connections[ path ] || []; connections[ path ] = connections[ path ] || [];

we are performing a check to see if connections[ path ] === null or if connections[ path ] === undefined , if this is the case we assign connections[ path ] to an empty array.

With messages[ path ] we perform the same check and if it is null or undefined we assign it the value of { version: 0, body: ''}

For example, Let the connection and messages be the objects as below.

var connections={
  "path":"http://www.xyz.com",
  "version":"1.2.0"
};
var messages={ 
     "text':"This is message",
     "path":"http://www.xyz.com",
     "version":'1.2.0',
     "body":""
 };

Now the code below works as below: 1.path is assigned blank string if it is not present in object mentioned above. 2.Similarly, Path of messages will be path present in the object 'Path'. Otherwise, it will be an object of 'version' and 'body'

connections[ path ] = connections[ path ] || [];
messages[ path ] = messages[ path ] || { version: 0, body: ''};

connections and messages are just a JSON representation of javascript object. So, connections[path] is same as connections.path. Sign || used to assign blank values if actual value is not present or undefined in the object.

I should to provoke your imagination

a || b returns first element which not contain an any kind of false value.

connections[ path ] || []; 
//  return [] ( empty array) if connections[ path ] is return false ( or undefined, 0, [], "", NaN etc)

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