Search code examples
javascriptd3.jsreturnor-operator

Javascript return OR with assignment of value?


I'm working with a simple example in D3, and I've been puzzling over this return statement for a while.

function nodeByName(name) {
    return nodesByName[name] || (nodesByName[name] = {name: name});
}

I have a basic understanding of using the || operator in a return statement, but please correct me if I'm wrong. From what I have gathered, if nodesByNames[name] is undefined, then a new object nodesByName[name] is created with a name of name.

What I'm trying to get at is that I don't know how to wrap my mind around returning an assignment like nodesByName[name]={name:name}.


Solution

  • When you use the || operator to create an expression (i.e. a || b), JavaScript will return either the first operand that evaluates to something truthy, like 1 or true or any object, or else will return the last value. (So a || b || c will return c if all of the values are false).

    In your example, you have this:

    nodesByName[name] || (nodesByName[name] = {name: name})
    

    Javascript will start by evaluating the left hand side, nodesByName[name]. If this value is something truthy, it will be returned. If it is not, (and undefined is not), the right hand side will be evaluated and returned. The right hand side is an assignment, which will return an object, {name: name}, after assigning it to nodesByName[name].

    The reason for having this chunk of code is to assign a value to nodesByName[name] if it does not already have a value.