Check out our Angular Book Series.

Creating Variables in TypeScript - Part 2

I'm working on a longer series of articles about Typescript. This will be extra material to support my upcoming Angular 4 book. This is the second part of that series. Check out part 1.

An important part of programming is the ability to create variables. Let's turn our "Hello World" Variable into a variable. First, we'll do it the Javascript way and then we'll modify it with some TypeScript.

Create a Variable

This is the original demo from the previous section:


function echo(message) {
return message;
}
document.body.innerHTML = echo("Hello World");

We can easily add a variable in here. First, create the variable:


var message ="Hello World"

The var keyword is the normal way to create a variable in JavaScript. Now, modify the echo() call to pass the variable instead of the string:


document.body.innerHTML = echo(message);

Recompile the code and it will work just as the previous sample:

Define the Variable with Let instead of Var

TypeScript includes a secondary way to create a variable, using the let keyword instead of the var keyword:


let message ="Hello World";

This simple replaces the var command with the let command. Recompile and you'll see the same results. Let is part of the ECMAScript 6 standard, but for maximum compatibility, you probably want to stick to ECMAScript 5 or lower compatibility.

The reason to use the let command instead of var is because the two scope differently. When you use var the new variable is created as part of the function block. If the variable is not part of the function block it is added to the global scope of the page. This is why it is considered a best practice for a lot of code to be included in an IIFE. This can cause unexpected results in some cases, such as when you access loop counters inside nested for loops, or have one function embedded in another. The let keyword always scopes at the block level, so each for loop would be considered its' own block.

Consider this code:


function scopedemovar(){
for(var i = 0; i <10; i++){
console.log('outer i: ' + i);
for(var i = 0; i <10; i++){
console.log('inner i: ' + i);
}
}
}
scopedemovar();

Although this might be considered nonstandard code because the counter variable for both loops is defined twice and identical it is still perfectly valid. What would you expect the output to be? Try it and run it:

You may expect the outer loop to loop 10 times, but it only loops once. That is because the inner loop changes the value of the counter variable and the stop condition triggers the second time the outer loop tries to run.

Change the var to let:


function scopedemolet(){
for(let i = 0; i <10; i++){
console.log('outer i: ' + i);
for(let i = 0; i <10; i++){
console.log('inner i: ' + i);
}
}
}

Now, each i variable is scoped to its own for block and they do not interfere with each other:

I cut off the full output since it was very long, but you can run the code to see that both the inner and outer loop both execute a full 10 times using the let value.

Add Typing to Variables

An important decision for using TypeScript is to make variables statically typed instead of dynamically typed. We can add a type to the variable definition, like this:


let message : string ="Hello World";

We can change the function definition too:


function echo(message:string ):string {
return message;
}

The function now includes a typed argument and an explicit return type. When we send in the message variable the compiler checks to make sure that we are sending in a string. Recompile the code and run it. You'll see no differences in the output:

Open up the JavaScript file created by the TypeScript compiler for a bit of a surprise:


function echo(message) {
return message;
}
var message = "Hello World";
document.body.innerHTML = echo(message);

All your type statements were stripped out. That is because these types are part of TypeScript, but not JavaScript. They allow for compile time checking of values, but do not change the underlying language or how things run in the browser. This is an important distinction to remember as you learn TypeScript. The language is all about improved tooling and compile time validation; not about a new language in the browser.

Keep up to date by reading DotComIt's Monthly Technical Newsletter

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.