2

I've recently came across this particular code:

const arr = [1,2,3];
const { length } = arr;
for (i = 0; i<=length; i++){
    console.log(i)
}

Apparently this (const { length } = arr;) somehow works, but I haven't found any information on the Internet on either how or why should this actually work.

My question: how does this { } construction work and why doesn't it work when I change { length } to anything else, like { arrlength }? Can we possibly use this construction with other array's properties and how?

JoshJohnson
  • 263
  • 11
  • 4
    This is [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). `const { length } = arr` is equivalent to `const length = arr.length` – Dan Nov 03 '20 at 17:27
  • While that works, that's really weird. `i <= arr.length` works just find without an extra variable – Taplar Nov 03 '20 at 17:28
  • @Dan so we can define array's length by simply assigning array to an empty variable? – JoshJohnson Nov 03 '20 at 17:28
  • No the variable name should be `length` – Sarun UK Nov 03 '20 at 17:29
  • Why can't we use another `const` name though, I'm really confused)) – JoshJohnson Nov 03 '20 at 17:30
  • 1
    This is an example of code being "too fancy". There are more concise ways to do this. Just because you can, doesn't mean you should. – Taplar Nov 03 '20 at 17:30
  • See also [Javascript object bracket notation ({ Navigation } =) on left side of assign](https://stackoverflow.com/q/26999820/215552), my preferred canonical when the user doesn't know about destructuring. – Heretic Monkey Nov 03 '20 at 17:31
  • 1
    Because `const { arrlength } = arr` is equivalent to `const arrlength = arr.arrlength`. If you want to create a varaible that is different to the property name, you need to use `const { length: arrlength } = arr` Please go through duplicates and the link added by @Dan in the first comment – adiga Nov 03 '20 at 17:31
  • Ooh, thank you @adiga – JoshJohnson Nov 03 '20 at 17:32
  • 1
    the destructuring assignment is *not* defining the arrays length. the arrays length is determined by the array literal. all the assignment is doing is creating a variable named length which has the value of `array.length` assigned to it at time of assignment. – Dan Nov 03 '20 at 17:32
  • Thank you, didn't know about this until now – JoshJohnson Nov 03 '20 at 17:33
  • @Taplar Airbnb styleguide forces this [How to fix Eslint error “prefer-destructuring”?](https://stackoverflow.com/questions/47395070) – adiga Nov 03 '20 at 17:36
  • `for (i = 0; i < arr.length; i++)` you don't need an extra variable at all – Taplar Nov 03 '20 at 17:37
  • @Taplar valid point – adiga Nov 03 '20 at 17:38

0 Answers0