let and const
- TypeScript course
- Beginner
- Lesson 9/89
- 4 min
Learn the difference between let and const and type inference.
The difference between let and const
A variable declared with let can be reassigned later; one declared with const cannot be changed after its initial value. Which you use depends on whether the variable will change.
let yas = 25;
yas = 26; // valid
const PI = 3.14;
PI = 3; // errorPrefer const when possible; it prevents accidental changes.
Type inference
When you give a variable an initial value, TypeScript infers the type from that value automatically even without a type annotation. This is called type inference.
let sehir = "İzmir"; // string
const PI = 3.14; // number
let aktif = true; // booleanType inference keeps code short, but writing the type explicitly is also fine.
Practice const and let together
Declare a const variable PI with value 3.14 and type number. Declare a let variable yaricap with value 5 and type number. Reassign yaricap to 10. Then print PI * yaricap * yaricap with console.log.
Starter code
// PI'yi const olarak 3.14 ile tanımla
// yaricap'i let olarak 5 ile tanımla
// yaricap'i 10 olarak yeniden ata
// PI * yaricap * yaricap yazdırSample solution
const PI: number = 3.14;
let yaricap: number = 5;
yaricap = 10;
console.log(PI * yaricap * yaricap);Expected output
314
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which line of the following code raises an error?
const PI = 3.14;
let x = 5;
PI = 3;
x = 10;- Line 2
- Line 3 Correct answer
- Line 4
- Line 1
Explanation: A variable declared with const cannot be reassigned, while one declared with let can. Therefore line 3 (PI = 3;) raises an error.
2 Choose the right keyword
____ fiyat = 100;
fiyat = 120;
let fiyat = 100;
fiyat = 120;
Explanation: Because the variable is reassigned later, let should be used; const would cause an error.
3 let and const concepts
| Term | Meaning |
|---|---|
let |
reassignable |
const |
cannot be reassigned |
let x = 5 |
type inference: number |
const y = "a" |
type inference: string |