My question is: why function results appears before for loop in browser console? It should run for loop (1, 2, 3, 4, 5), but it run ('cool' and 1!2!3) first, so below I add my code and console result. I'll be very thankful if someone can explain me this behaviour. It is not a duplicate, because, I want to understand how it works, not to make it work. In suggested question there is a solutions to run for loop with setTimeout first, but not explain behaviour completely.
// Loops + Closure
for (let i = 1; i <= 5; i++) {
setTimeout(function timer() {
console.log(i)
}, i * 1000)
}
//Modules
function CoolModule() {
let something = 'cool'
let another = [1, 2, 3]
function doSomething() {
console.log(something)
}
function doAnother() {
console.log(another.join('!'))
}
return {
doSomething: doSomething,
doAnother: doAnother
}
}
let foo2 = CoolModule()
foo2.doSomething() // 'cool'
foo2.doAnother() // 1 ! 2 ! 3