Javascript, what does this do ? var com = com || {};

In this, is com either com or nothing , and how ?

var com = com || {};

com either becomes the value of com (if it isn’t undefined or null), otherwise, it becomes an empty object (hence the || {}, that simply means, if com is null or undefined, give it an empty object to be initialized as.

1 Like

JavaScript has a couple of shorthand conventions.

The default clause uses the OR operator so that assignment occurs up until a falsy value occurs. It’s commonly used to replace a falsy value A falsy value is any of undefined, null, false, 0, “”, NaN.

Your above code sample is equivalent to the following:

if (com) {
    com = com;
} else {
    com = {};
}

Another one you will commonly come across is the guard clause, that prevents the latter conditions from being checked while the earlier ones are falsy.

For example:

if (form && form.elements.someField) {
    // do stuff in here
}

which is equivalent to:

if (form) {
    if (form.elements.someField) {
        // do stuff in here
    }
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.