let and const in TypeScript#

let and const#

Prior to ES2015, JavaScript variables were declared using the 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:

The variable 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 0 through 2, and the console.log() statement would throw an error as i should not exist outside of the for-loop.


This page is a preview of Beginners Guide to TypeScript

Start a new discussion. All notification go to the author.