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.
- What is a variable
- How to declare a variable
- How to assign a value to a variable
- How to initialize a variable with a value
- How to use a variable
- How to change the value of a variable
- What is a constant
- How to initialize and use a constant
- Operands: lvalues and rvalues
- Var vs Let: What's the difference
- Summary: Points to remember
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.
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.
// with type
var name: type
// without type
var name
We can also use the let keyword to declare a variable.
// with type
let name: type
// without type
let name
We’ll talk about the difference between the two in a little bit.
As an example, let’s define a variable called msg1 of type string and a variable called msg2 that doesn’t have a type.
// with type
let msg1: string
// without type
let msg2
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 = (equals) operator and lastly, the value we want to store.
name = value
note We don’t use the var or let keywords. The variable already exists, we’re just adding a value to it.
// declaration
let msg1: string
let msg2
// assignment
msg1 = "Hello, World!"
msg2 = "Hello there"
In the example above we use our two variables from before and assign short strings to them.
The msg2 variable 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.
// 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
This time for the example, let’s assign values directly to the variables when we declare them.
let msg1 : string = "Greetings"
let msg2 = "humans!"
How to use a variable
To use a variable, we simply refer to its identifier wherever we need to use it in our code.
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.
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.
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 result by performing a different calculation.
When we compile and run the script, we see on the second line that the value has changed.
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.
// const with type
const NAME : type = value
// const without type
const NAME = value
tip As we mentioned in our Basic Syntax lesson, the convention for naming constants is all uppercase letters with multiple words separated with underscores.
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.
tip 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.
// 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.
// 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.
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.
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.
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 script, it will print the value twice.
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 or let keywords can be used to declare or 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.