+ 4

Could someone explain to me what's going on in this code?

https://code.sololearn.com/WGblY0WKegAj/?ref=app

5th Apr 2021, 4:09 AM
Ayoob Saad
Ayoob Saad - avatar
3 odpowiedzi
+ 5
That code uses fairly new features of JavaScript. I modified the code to show more outputs which should make the behaviour easier to trace: arr = [] for (let {x=3, y=2} of [{x:1},{y:4}]){ console.log('x = ' + x + ', y = ' + y); arr.push(x,y) } console.log(JSON.stringify(arr)); arr.forEach(k => console.log(k) ) Here is the output: x = 1, y = 2 x = 3, y = 4 [1,2,3,4] 1 2 3 4 The following loop iterates 2 times. Once for {x:1} and once for {y:4}. for (let {x=3, y=2} of [{x:1},{y:4}]){ Out of the above, it is important to note the usage of a recent JavaScript feature called "destructuring assignment". Here, x is a variable declared here that will take the value of the x property of the assigned object. If the assigning object doesn't specify a value for its 'x' key/property, the value is defaulted to 3. Likewise for y. More can be learned about destructuring assignments from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment In first iteration, y isn't specified in the object {x:1} so y is defaulted to 2. The resulting x is 1. y is 2. arr.push(x, y) will push 2 new values into the Array. arr will become: [1, 2] In second iteration, x isn't specified in the object {y:4} so x is defaulted to 3. The resulting x is 3, y is 4. After arr.push(x, y), arr will have the value [1, 2, 3, 4]. Then there is a loop to print every value from the arr. forEach is a method of all Array that runs the specified function once per array element so once for 1, then 2, then 3, then 4. More can be learned about the forEach method at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
5th Apr 2021, 4:30 AM
Josh Greig
Josh Greig - avatar
+ 1
So that's why i couldn't find it on YouTube, thank you so much, i will check the documentation as well
5th Apr 2021, 5:04 AM
Ayoob Saad
Ayoob Saad - avatar
+ 1
That was a great explanation, with the help of the first 5 lines of the documentation
5th Apr 2021, 5:13 AM
Ayoob Saad
Ayoob Saad - avatar