let and const in TypeScript
const in TypeScript#
var keyword. When declaring variables with
var, those variables are not block scoped, meaning variable declarations within if-statements and loops are visible outside of those blocks.
The classic example--and a common interview question--of when
var declarations are problematic involves a for-loop that uses
setTimeout() to print a variable:
After one second has passed, the output of the code above will be the following:
i is shared between each iteration of the loop and
i persists even after the for-loop is done executing. If the code were working as intended, our output would print
2, and the
console.log() statement would throw an error as
i should not exist outside of the for-loop.