3

I came across this code:

function extend(out){
    out = out || {};
    for (var i = 1; i < arguments.length; i++){
        var obj = arguments[i];
        if (!obj) continue;
        for (var key in obj){
            if (obj.hasOwnProperty(key))
                out[key] = (typeof obj[key] === 'object') ? extend(out[key], obj[key]) : obj[key];
        }
    }
    return out;
}

What does the line out = out || {}; mean and how does it work?

This function bascially combines different objects into one object.

yqlim
  • 6,898
  • 3
  • 19
  • 43

5 Answers5

1

It sets a default value for out, ie if out is not provided to the function, (or it is a falsy value such as false, 0, null, undefined or ''), then out is assigned {}.

How it works: Javascript uses short circuit evaluation, which means the the or (||) operator will return the first non-falsy value. If out is not falsy, nothing changes, if out is falsy, it gets set to {}.

dtkaias
  • 781
  • 4
  • 14
1

In Javascript, the || operator returns the first operand if it is a truthy value; otherwise, it returns the second. So in context here, if out is a falsy value (such as undefined), then out = out || {} will assign {} to out; otherwise, it will assign the current value of out into out, which effectively does nothing.

The intent is to provide a default value for out. If the caller passes false, null, or undefined as the first argument, then out will be a new object. If the caller passes an object as the first argument, then the function will modify that object.

Thom Smith
  • 13,916
  • 6
  • 45
  • 91
0

It is basically the short hand of doing this

if(!out){
    out = {};
}

Essentially if out does not evaluate to 'true' then out will be set to an empty array in this case.

Already answered here also: What does the construct x = x || y mean?

Community
  • 1
  • 1
Aidan
  • 757
  • 3
  • 13
0

That is a simplified form of this:

function extend(out){
    if (!out) {
        out = {};
    }
    ...
}
Teocci
  • 7,189
  • 1
  • 50
  • 48
0
out = out || {};

If the variable 'out' is not set prior to this line, the value will be set to an empty array. JavaScript OR (||) variable assignment explanation

Community
  • 1
  • 1
L L
  • 1,440
  • 11
  • 17