Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is “for(const [[[[[a, b, c]]]]] in [0, 0]);” even valid?

Tags:

Writing dumb code, I've just found something weird.

for(const [[[[[fancy, loop]]]]] in [0, 0]) {    console.log(fancy, loop);  }
// Chrome 70.0.3538.77 says: // 0 undefined // 1 undefined 

It's like assigning 0 and 1 to [[[[[fancy, loop]]]]], which, is array destructurings taking place and supposed to throw an error, isn't it? Or not. It's just my thought getting me confused right now.

Could you please tell me how it is valid and works with no error? What am I missing?

like image 931
Константин Ван Avatar asked Nov 05 '18 00:11

Константин Ван


2 Answers

It's not assigning 0 and 1 to [[[[[fancy, loop]]]]]. You're looping over the keys of [0, 0], because you used in instead of of, and those keys are strings.

The string "0" is an iterable whose sole element is "0". Assigning "0" to [[[[[fancy, loop]]]]] repeatedly unpacks "0" and gets "0", until eventually it gets down to

[fancy, loop] = "0" 

at which point the final unpacking assigns "0" to fancy and undefined to loop.

like image 198
user2357112 supports Monica Avatar answered Sep 30 '22 04:09

user2357112 supports Monica


You're using in instead of of so you're getting the properties of the array not the values. For this case you're getting the array indexes as strings (0, 1). You're basically destructuring a string with length of 1 every time. So you always get the first character of every iterated property

like image 27
lleon Avatar answered Sep 30 '22 06:09

lleon