Bitpath

Lesson 2 · Unit 01

Variables and types

Names for values, and the compiler that checks them

13 exercisesabout 3 min

What you practise

  • let and const, number, string and boolean, 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?

TypeScript
let price = 4;
console.log(price * 2);

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.

TypeScript
let score = 10;
score = 15;
console.log(score); // 15

Concept

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.

TypeScript
let age = 30;        // number
let city = "Oslo";   // string
let open = true;     // boolean

Concept

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.

TypeScript
let age: number = 30;
let city: string = "Oslo";
let level = 2; // worked out: number

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy