asd123ea
asd123ea

Reputation: 131

Javascript assining a function to other function on if

I'm reading a Nodejs book and I came accross to this syntax below

function createClient (ns, opts) {
  return createClient[ns] || (createClient[ns] = nos(net.connect(opts)))
}

Didn't quite understand the createClient[ns] = nos(net.connect(opts)) part, What it means? Why should I use it?

Is this syntax documented anywhere?

Upvotes: 0

Views: 54

Answers (1)

chuckx
chuckx

Reputation: 6877

This is taking advantage of the ability to chain the assignment operator to assign values to multiple variables at once. Stated another way, the return value of an assignment expression is the value that was assigned.

The simplest demonstration is to the log the output of an assignment operation:

console.log(test = 'foo');

This behavior is mentioned in the MDN docs for the assignment operator:

Chaining the assignment operator is possible in order to assign a single value to multiple variables

In your code snippet, the intention seems to be "return the value of createClient[ns] unless it's false (e.g. unassigned), otherwise assign the value of nos(net.connect(opts)) to createClient[ns] and return that value."

This is a simple form of caching and implies that nos() is an expensive operation that shouldn't be repeated unless necessary.

Here's a simplified example:

let values = {};

function assignIfNotSet(arg) {
  return values['example'] || (values['example'] = arg);
}

console.log('before:');
console.log(values);

let result = assignIfNotSet('foo');

console.log('after:');
console.log(values);

console.log('result: ' + result);

Upvotes: 2

Related Questions