TypeScript Variables & Constants Tutorial

In this TypeScript tutorial we learn about temporary data containers called variables and constants that store values in memory when the app runs.

We learn how to declare and initialize variables and constants, how to use them and how to change variable values.

Laslty we discuss operands, lvalues and rvalues and the difference between the var and the let keywords.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a variable

A variable is a temporary data container that stores a value in memory while the application is running.

Consider a calculator app. When we perform an addition for example, the app stores the result in a variable which we can use to perform additional calculations.

Example:
3 + 5 = x

x * 8 = y

In the example above, the letters ‘x’ and ‘y’ store the resulting data from the arithmetic.

Variables are used all over our apps to store runtime data. When the app is closed, or the variable is no longer used by the program, the value in memory is removed.

How to declare a variable

To create a variable without a value, we use one of TypeScript’s special keywords, var . This is known as variable declaration.

We can create the variable in one of two ways, with a type, or without.

Syntax:
// with type
var name : type;

// without type
var name;
Example:
// with type
var msg1 : string;

// without type
var msg2;

In the example above, we define a variable called ‘msg1’ of type string and a variable called ‘msg2’ that doesn’t have a type.

How to assign a value to a variable

Now that we have variables, we can store values in them. This is known as assignment.

To assign a value to a variable, we write the name of the variable, followed by the = operator and lastly, the value we want to store.

Syntax:
 name = value;

Note that we don’t use the var keyword. The variable already exists, we’re just adding a value to it.

Example:
// declaration
var msg1 : string;
var msg2;

// assignment
msg1 = "Hello, World!";
msg2 = "Hello there";

In the example above we use our two variables from before and add short strings to them.

The variable ‘msg2’ wasn’t declared with a type, but when we assigned a value to it, the compiler automatically inferred the type of string because the value we assigned was a string.

How to initialize a variable with a value

We don’t have to declare a variable and assign a value to it afterwards, we can do both in a single step. This is known as initialization.

There are two keywords we can use when we initialize a variable with a value, var and let .

Syntax:
// var with type
var name: type = value;

// var without type
var name = value;

// let with type
let name : type = value;

// let without type
let name = value;

The initialization is exactly the same for both, its just the keywords that are different.

Example:
// var initialization
var msg1 : string = "Greetings";
var msg2 = "humans!";

// let initialization
let msg3 : string = "We come"
let msg4 = "in peace"

This time, we assign values directly to the variables when we declare them.

How to use a variable

To use a variable, we simply refer to its identifier wherever we need to use it in our code.

Example:
let num1 = 5;
let num2 = 3;

let result = num1 + num2;

console.log(num1, " + ", num2, " = ", result);

In the example above, we initialize two variables with numbers, then add them together and store the result in another variable.

Then, we print them all to the console with the console.log() function.

Output:
 5  +  3  =  8

How to change the value of a variable

Variables in TypeScript are mutable, which means we can change their values while the application is running (at runtime).

To change the value of a variable, we simply assign it a new one with the assignment operator.

Example:
let num1 = 5;
let num2 = 3;

let result = num1 + num2;

console.log(num1, " + ", num2, " = ", result);

// mutate variable
result = num1 * num2;

console.log(num1, " * ", num2, " = ", result);

This time we change the value of the ‘result’ variable by performing a different calculation.

When we compile and run the script, we see on the second line that the value has changed.

Output:
5  +  3  =  8
5  *  3  =  15

What is a constant

A constant is a variable that cannot have it’s value changed during runtime.

We use constants when we do not want a value to accidentally change, like the value of Pi, or gravity.

How to initialize and use a constant

A constant cannot be declared without a value because a value cannot be assigned later on, and there would be no point to an empty constant.

To initialize a constant with a value, we use the const keyword.

Syntax:
// const with type
const NAME : type = value;

// const without type
const NAME = value;

As we mentioned in our Basic Syntax lesson, the convention for naming constants is all uppercase letters with multiple words separated with underscores.

Example:
const PI : number = 3.14159;
const RADIUS = 1.6;

// circumference of circle
let circum = 2 * PI * RADIUS;

// area of circle
let area = PI * RADIUS * RADIUS;

// print
console.log("Circumference: ", circum);
console.log("Area: ", area);

In the example above, we declare two constants for values that we don’t want to change while the script runs. Then we use them all over the script just like we would a variable.

Constants are the same as variables, except their values are immutable, they cannot change during runtime.

Operands: lvalues and rvalues

TypeScript has two types of expressions, lvalues and rvalues.

The operand on the left side of the assignment operator ( = ) is the Lvalue, and the operand on the right side is the Rvalue.

Lvalue:

An Lvalue can have a value assigned to it so it’s allowed to appear either on the left or the right side of an assignment.

Example: lvalue
// lvalue (num1) may
// be on the left
let num1 = 10

// or on the right of the =
let num2 = num1

Rvalue:

An rvalue cannot have a value assigned to it so it may only appear on the right side of an assignment.

Example:
// rvalue (10) may only be on the right
let num1 = 10

// and cannot be on the left
10 = 10

Var vs Let: What’s the difference

The important difference between var and let is that let can only be used in a local scope.

Let’s see an example, then explain what’s happening.

Example:
if (true) {

  // 'a' belongs to the
  // local scope and cannot
  // be used outside of the
  // curly braces
  let a = "Hello there";
  console.log( a );
}

console.log( a );

In the example above, we define a local scope with the curly braces of the if statement and initialize the variable ‘a’ inside.

When we try try to use ‘a’ outside of the curly braces in the second console.log() function, the compiler raises an error.

Output:
main.ts:10:14 - error TS2304: Cannot find name 'a'.

10 console.log( a );

The error states that it cannot find the name ‘a’. That’s because the second console.log() function doesn’t know that ‘a’ exists, it can’t see inside the curly braces.

If we change the keyword from let to var, we are allowed to use ‘a’ outside of the if statement’s scope.

Example:
if (true) {

  var a = "Hello there";
  console.log( a );
}

console.log( a );

This time, the compiler doesn’t raise an error and if we run the .js script, it will print the value of ‘a’ twice.

Output:
Hello there
Hello there

Summary: Points to remember

  • Variables and Constants are temporary data containers.
  • We can specify a type for our variables and constants or we may omit it.
  • The var keyword is used to declare a variable.
  • The var or let keyword is used to initialize a variable.
  • The const keyword is used to initialize a constant.
  • Constants can only be initialized with a value, not declared empty.
  • Values stored in variables are mutable.
  • Values stored in constants are immutable.
  • To use a variable or constant, we simply refer to its name.