How come the first program outputs 333 and how could have the second program resulted to false? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

How come the first program outputs 333 and how could have the second program resulted to false?

//First program for(var i = 0; i < 3; i++) { setTimeout (function() { document.write(i) } , 200); } //Second program var info1={ "planet":"Earth", "suitable For Living":true }; var info2={ "planet":"Earth", "suitable For Living":true }; alert(info1===info2 || info1===info2);

9th Jul 2019, 3:53 PM
eMBee
eMBee - avatar
6 Answers
+ 6
First: It outputs the variable i. i at that moment is 3, therefore the output will be 333. Second: You might have heard of this, but objects are.compared by their reference. This means, that info1 and info2 are 2 different objects, with the same properties. Two objects are never equal unless you specifically assign them to.
9th Jul 2019, 4:31 PM
Airree
Airree - avatar
+ 5
Okay, I got you Airree for the second explanation but for the first one, you didn't mention how "200" is affecting the code's output. Please elaborate on that, thanks in advance
9th Jul 2019, 7:17 PM
eMBee
eMBee - avatar
+ 5
Sonic yes
11th Jul 2019, 9:11 AM
eMBee
eMBee - avatar
+ 3
Okay. The setTimeout function is an asynchronous function, meaning it's not like a normal function, that just runs, and then the program continues; but it will move this function to the back of the execution of the program, waits the time (in miliseconds), and THEN executes it. It would be the same if it would be 0. After the program execution ends, it will check i, and it's 3 so it'll print it
9th Jul 2019, 7:22 PM
Airree
Airree - avatar
+ 3
Mofey I guess that after the timeout, the loop has already completed and the value of the i variable is 3, which means that all 3 calls to the function will output 3. Also in your second program, did you intend to write === for both conditions?
11th Jul 2019, 4:10 AM
Sonic
Sonic - avatar
- 4
🖕🖕🏼
11th Jul 2019, 7:36 AM
Dikshit
Dikshit - avatar