TL ; DR:
Variables are containers for storing values. You create a variable using the let keyword.
This is how you create a variable named car and initialize it with string "Toyota":
let car = "Toyota";
This is how you create a variable named experience and initialize it with number 3:
let experience = 3;
Full lesson:
Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.
Variable creation:
We tell TypeScript to create or declare a variable by putting the keyword let in front of the variable's name, like so:
let name;
creates a variable named name.
Variable initialization:
We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:
let name = "AlgoCademy";
creates a new variable named name and assigns it an initial value of "AlgoCademy".
When executing this code, TypeScript (after it is compiled to JavaScript) will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.
You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.
Accessing values in variables:
Now we can use this label anywhere in our program to access the value in that box. We can print it for example:
// We create and initialize two variables:
let name = "AlgoCademy";
let age = 10;
// We access the variables:
console.log(name);
console.log(age);
The output of this code is:
AlgoCademy
10
Undefined:
In the first piece of code, we have created the container name. That container was empty, we didn't put any data inside it.
In other words, we have created the variable name, but we haven't assigned any value to it yet.
And so, the output of this code:
let name;
console.log(name);
would be:
undefined
The undefined value indicates that a variable has not been assigned a value.
We'll learn much more about this in future lessons, but we want to avoid having undefined values in our programs as much as possible.
Important notice:
We almost never want to create a variable without initializing it! It's a bad coding practice and can cause a lot of problems.
Type annotations:
TypeScript lets you add an optional type annotation after a variable's name, separated by a colon. It tells the compiler exactly what kind of value the variable holds. You still use const and let just like in JavaScript.
let count: number = 5;
let isOn: boolean = true;
const car: string = "Toyota";
You'll see annotations like : number, : boolean, and : string throughout the coding tutorials.
Assignment
Follow the Coding Tutorial and let's create some variables.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
