0

Can Anyone explain the code???

(function () { let w = 6; setTimeout(()=>{ w += 3; }); alert(w); })()

20th Jan 2020, 4:40 AM
Sachin Shah
Sachin Shah - avatar
6 Answers
+ 2
About IIFE Ipang is right, but setTimeout (as well as setInterval) with no delay specified default to zero (well, in reality default to about 4ms wich is the minimal delay) run his function argument only when all current running code is done... only after that the setTimeout/setInterval queue is executed. So, when the line "alert(w)" is executed the "w" value is not still "altered" and display its original value (6) ^^ https://javascript.info/settimeout-setinterval
20th Jan 2020, 5:39 AM
visph
visph - avatar
+ 1
This is an example of Immediately Invoked Function Expression, it is where you define a function and invoke it at the same time, or rather immediately after the definition. You define an anonymous function, wherein you define a variable <w> and assign it value 6. Next you call setTimeout passing an anonymous function argument which will add 3 to the value of <w>. There is no milliseconds wait time set when calling setTimeout, so setTimeout will execute the anonymous function argument after the rest of the code, including the `alert` popup has been completely processed. Then you display alert dialog showing the value of <w>, which remains the same because `alert` is called prior to the queued anonymous function (setTimeout argument). https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript (Edited)
20th Jan 2020, 5:17 AM
Ipang
+ 1
Ipang no problem: nobody's perfect ;) if you feel my correction not kindly, please excuse me: my english is not enough subtle to say things kindlier :(
20th Jan 2020, 6:03 AM
visph
visph - avatar
0
visph Thank you for correction, I didn't know about the minimum wait time, and forgot the instruction queue priority. * I have edited my previous response, kindly note me for any further need of edits.
20th Jan 2020, 5:54 AM
Ipang
0
Don't worry visph , your correction is kindly. I've seen and read people do it in "better" way when suggesting correction before, so it's okay 👌
20th Jan 2020, 6:12 AM
Ipang
0
6 will be alert and w not changed
22nd Jan 2020, 1:56 AM
Elsayed Elkadey
Elsayed Elkadey - avatar