0

i was taking lessons on ES6 key features but this snippet is troubling my common sense, how does javascript resolve ",b" to be the 2nd item in the return array of the foo function does b in the case implicitly mean 2nd item and z would mean 26th item ?? See code snippet below ...

    function foo() {
 return [1,2,3];
}


function bar() {
 return {
 x: 4,
 y: 5,
 z: 6
 };
}


var [,b] = foo();
var { x, z } = bar();
console.log( b, x, z );

// 2 4 6

Code Snippet

Yusuf
  • 9
  • 4
  • 4
    Please post code as text (with [appropriate formatting](https://stackoverflow.com/editing-help#code)), not a link to a painting of it. – Bergi Jun 16 '22 at 15:47
  • No, the ordinal value of the single-letter variable name is irrelevant. – jarmod Jun 16 '22 at 15:49
  • "*how does javascript resolve ",b" to be the 2nd item in the return array*" because it's the second element in the array on the left side (with the first being ignored ...) – derpirscher Jun 16 '22 at 15:50
  • "*z would mean 26th item*" - no idea how you get there. No, `z` in object destructuring refers to the property named `"z"`. And in array (iterable) destructuring, it all depends on the position. – Bergi Jun 16 '22 at 15:51

1 Answers1

0

The lettering does not matter. What matters is the comma.

var [b] would destructure the first element from the array returned by foo().

var [,b] destructures the second element from the array

var [, , b] would destructure the third element.

boc4life
  • 941
  • 5
  • 10