0

NOTE: I've looked at this identically named question and several others. My question is somewhat different.

I was reading an article and came across a JS pattern I hadn't seen before. I've been trying to play with it (details below), and it still doesn't make sense. Searches have also come up dry.

Here's the pattern (the code referenced in the above article). The specific line:

return 'The error is', err;

I tried to reproduce this somewhat more simply (while reproducing the basic context in case that was part of what was going on) in the console:

obj = {
    resolve(whatever, another) {
      console.log(whatever, another);
      return 'The error is', whatever;
    }
}

The first attempt is a single variable to catch the return:

a = obj.resolve('Hey', 'there');
Hey there // What is console logged
"Hey" // The return -- NOT "The error is"
a
"Hey" // a value equals the return

Then I tried to access both return values as a destructured array:

[b, c] = obj.resolve('Whats', 'up');
Whats up // What is console logged
"Whats" // The return value
b
"W" // b value
c
"h" // c value

Finally, for kicks, I tried object destructuring:

{d, e} = obj.resolve('Another', 'one');
Uncaught SyntaxError: Unexpected token =

To confirm that it seems to return only the last value, I tried this as well:

function func (arg) {
  return 'First', arg, 'Third';
}

z = func('hello')
"Third" // The return
z
"Third"

Does anyone know what's going on here/how JavaScript reads this code? It looks like only the final value is returned. Is there documentation on how this works? Is there any reason at all to use this pattern? It seems like everything other than the last return value is ignored.

Sasha
  • 6,224
  • 10
  • 55
  • 102

0 Answers0