0

While doing some exercises on JavaScript ES6+ I came across a syntax I did not understand. In the below code, how come the length property in {name:{length:l}} is not prefixed by the object and a DOT? I'm used to seeing the length property used like this: str.length;

Note: I'm using console.log just to see the values.

const bob = { name: 'Bob' };
const alice = { name: 'Alice' };
const foundAt = [bob, alice].findIndex(({ name: { length: l } }) => console.log(l))
Bryan
  • 133
  • 1
  • 10
  • 1
    The code you have posted logs `0` twice. Because, you are creating a `l` variable with value set to `o.name.length`. So, `length` refers to [`window.length`](https://developer.mozilla.org/en-US/docs/Web/API/Window/length). So, if you `console.log(l)`, you should see `3` and `5` which are lengths of the strings – adiga Oct 01 '19 at 11:52
  • yes it is a typo. please ignore that part – Bryan Oct 01 '19 at 11:54
  • Window.length is 1 while the result of the above snippet is -1 because testing function does not provides results. – Mosè Raguzzini Oct 01 '19 at 11:55
  • i changed it to console.log(l) as u said – Bryan Oct 01 '19 at 12:07

1 Answers1

3

This is known as destructuring, useful to extract properties from arrays and objects.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • Okay so in the code they are just giving an alias "l" to length that already belongs to the object by default? – Bryan Oct 01 '19 at 11:59
  • Yes, its used because it's handy to avoid providing complete path every time or assigning it variable by variable. It additionally provides a clear shape of the object do you expect – Mosè Raguzzini Oct 01 '19 at 12:00