Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'var' and 'let' in Typescript 1.5

What exactly is the difference between using either 'var' or 'let' in Typescript? I know that 'let' allows the variable to be defined further into a scope without it being used outside of said scope. That is obviously a nice advantage for iterators in for loops. I know this is an ES6 definition, so compiling to ES6 should look nearly identical in terms of 'var' and 'let'.

But, when it compiles down into ES5 javascript which doesn't support 'let', what exactly is happening? Are there oddly named variables that the compiler creates so that it prevents using said variables in the context of the Typescript file? What happens in situations where you define many 'let' variables throughout a function? Is there a performance impact I should be concerned about?

Basically, what is happening when typescript compiles let variables to ES5 javascript?

like image 438
Zachary Dow Avatar asked Aug 15 '15 20:08

Zachary Dow


People also ask

Should I use VAR or let in TypeScript?

The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error.

What is difference between VAR and let in TypeScript?

The let declarations follow the same syntax as var declarations. Unlike variables declared with var , variables declared with let have a block-scope. This means that the scope of let variables is limited to their containing block, e.g. function, if else block or loop block.

What is declare VAR in TypeScript?

declare var d3 is how to declare a variable that exists somewhere in the JS. Think of it like "Yeah yeah typescript, quit complaining, trust me it exists". import {Component} from 'angular/core'; is how to pull a specific piece from a module. In node terms this translates to var Component = require('angular/core').


1 Answers

The easiest way to find answers to these type of questions to try it out in the TypeScript Playground.

TypeScript renames the variables within the block scope. There's no performance overhead compared to using regular variables defined with var.

This code:

var i = 0;
for (let i = 0; i < 5; i++) {}
i++;

Compiles to:

var i = 0;
for (var i_1 = 0; i_1 < 5; i_1++) { }
i++;

Here is some more information regarding let.

like image 168
thoughtrepo Avatar answered Oct 27 '22 00:10

thoughtrepo