I came across this destructuring expression in an article.
const words = ['oops', 'gasp', 'shout', 'sun'];
let { length } = words;
console.log(length); // 4
How does length
get the value of 4? I know .length
is a property of the array, but how does this syntax work? It seems to be doing let length = words.length;
and in fact in babel does output it as such. But my question is what is the logic behind it?
What is confusing me is the mix of an array of values and the the use of {length}
.
I have read MDN 's description but can't see this example explained.
Think of the code as being
const words = {0:'oops', 1:'gasp', 2:'shout', 3:'sun', length:4};
let { length } = words;
console.log(length);
Which it essentially is (nevermind all the other stuff arrays come with)
Does it make sense now?