Lesson 2 · Unit 01
Variables and types
Names for values, and the compiler that checks them
What you practise
letandconst,number,stringandboolean, an annotation against a type the compiler works out, template literals, the error you get before the program runs
Try a question from this lesson
Pick one
The first line gives the value 4 a name. What do you think this prints?
let price = 4;
console.log(price * 2);Correct answer
8
Why
let price = 4; creates a variable: a name that holds a value. Wherever price appears afterwards, the computer uses the value 4, so this is 4 * 2. No quotes around price: it is a name, not text.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Variables
let score = 10; creates a variable called score and stores 10 in it.
Later, score = 15; stores a new value. The old one is gone. Here = does not mean "is equal to". It means "store the value on the right in the name on the left".
You write let only once, when the variable is created.
let score = 10;
score = 15;
console.log(score); // 15Concept
Types and the compiler
Every value has a type. 5 and 3.5 are a number. "hi" is a string. true and false are a boolean.
A variable keeps the type of its first value for good.
Before a TypeScript program runs, a tool called the compiler reads all of it. If a line breaks a rule, nothing runs, and the compiler tells you which line.
let age = 30; // number
let city = "Oslo"; // string
let open = true; // booleanConcept
Writing the type yourself
You can state a variable's type after a colon. That is called an annotation.
Usually you leave it out: the compiler works the type out from the first value. Either way the result is the same, and the type is fixed.
An annotation is a promise the compiler checks: the value on the right must have that type.
let age: number = 30;
let city: string = "Oslo";
let level = 2; // worked out: number9 more exercises in the app
- 2× type the answer
- 1× true or false
- 1× match the pairs
- 3× multiple choice
- 2× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.