javascript - JS: Why does code run differently on the console than when it's on a .js file? -


i'm studying javascript, , book i'm following suggests easiest place test code (for exercises , exploring concepts) on browser console itself, that's i've been doing.

however, professional friend of mine told me instead make html page, link js file , put code want test there, inside invoked function. way load , reload page on browser see output on console.

i confused why same piece of simple code run or output differently if typed directly on console versus if loaded file.

then came across piece of code (used illustrate closure on loops) on material :

for (var i=1; i<=5; i++) {     settimeout(function timer(){          console.log(i);      }, i*1000 ); } 

the book says code should output number 6 5 times, when typed on console (google chrome) output 5, 5 6s (one per second).

remembering friend said, followed suggestion and, indeed, the same code, when executed js file linked html, outputs differently, resulting in number 6 5 times.

exactly why happen? difference on engine? compilation happen differently reason?

i have no idea what's @ play here. friend didn't have time or knowledge explain, , book never touches on subject.

the first 5 saw not result of of console.log() calls.

when type statement console, automatically prints value of last expression in statement. in case, printed value returned last call settimeout(), timer id.

if execute multiple times, you'll see first number increases each time.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -