Let, Const and Var in Javascript
JavaScript has three ways to make variables: let, const, and var.
They look similar, but they live in different places and follow different rules.
Scope means where a variable can be seen. Think of rooms in a house.
Global scope
Block scope
Function scope
let, const, and var
Global scope
A global variable is made outside every function and block.
Many parts of the program can see it.
It is like a toy left in the living room. Everyone can find it.
Block scope
A block is code inside curly braces { }.
let and const stay inside their block.
Outside the braces, those names are gone.
Function scope
var mostly cares about the whole function.
Inside one function it can be seen in many blocks.
Outside that function, it is hidden.
let
let is block scoped.
You can change its value later.
You should not make the same name twice in the same block.
const
const is also block scoped.
You must give it a value right away.
You cannot point the name at a brand new value later.
var
var is the older way.
It is function scoped and can be declared again.
That flexibility can surprise you, so most new code uses let or const.
Tip: Start with const. Use let when the value must change. Leave var for old code you are reading.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.