JavaScript
Difference between const and let
Learn reassignment and immutability concepts.
Reassignment
Giving a variable a new value later is called reassignment. A variable declared with let can be reassigned; one declared with const cannot.
For example, after let puan = 50; you can write puan = 75;; now puan holds 75. When reassigning you do not write let again; only the name, = and the new value.
The error of reassigning const
If you try to give a new value to a const variable, JavaScript throws a TypeError and the code stops. This is called immutability: const is bound to its value once and that bond cannot be broken.
For example, after const fiyat = 100; writing fiyat = 120; gives a TypeError. The error message is usually Assignment to constant variable. So when you pick const, make sure the value is truly constant.
When to use let, when to use const?
When you are sure a value will never change, use const: constants like pi, dogumYili or ulkeKodu. When the value may change, use let: things like puan, sicaklik or a counter.
This split gives a hint to anyone reading the code. When you see const you know the value stays the same until the end; with let you know it may change later. That is why modern JavaScript prefers const first, then let when needed, instead of var.
Exercise Declare puan, reassign it, print it
Declare a puan variable with let and give it an initial value (example: 50). Then reassign puan to a new value (example: 75). Finally print puan with console.log.
Show example solution
let puan = 50;
puan = 75;
console.log(puan);
Test yourself
-
Assign a new value to puan
let puan = 50;
____
console.log(puan); // prints 75
Show answer
let puan = 50;
puan = 75;
console.log(puan); // prints 75
-
Which of these code snippets throws a TypeError?
- const fiyat = 100;
fiyat = 120;
- let fiyat = 100;
fiyat = 120;
- let ad = "Alex";
console.log(ad);
- const sehir = "Izmir";
console.log(sehir);
Show answer
const fiyat = 100;
fiyat = 120; — Correct. A const variable cannot be reassigned; it throws a TypeError.
-
Match each use case to the right keyword
- Counter
- let (grows each step)
- PI constant
- const (stays fixed)
- Live temperature
- let (gets updated)
- Birth year
- const (cannot be set)
Next lesson: First data types