We can begin by knowing what they share in common, storing data. Imagine data as boxes.
Brief definitions for a general idea:
var
: used to store a box that will probably change later (mutable).
let
: similar to var
but a bit different (mutable).
const
: used to store a box that won't change later (immutable).
Block, Function, and Global scopes:
We've to first know what's scope
before knowing the difference between them.
scope
: the part of the code for which a variable is defined.
Examples:
Global scope
: anything outside of a function.
Block scope
: anything inside curly brackets {}
.
Function scope
: anything in a function.
function b() {
//Function scope
}
For now, you can think of each scope as its own room.
Difference between var
and (let
and const
):
In Global scope
: all of them can be accessed from other functions and blocks.
const a = 20
var b = 30
function c() {
console.log(a, b) // 20, 30
}
In Function scope
: var
, let
, and const
can't be accessed from outside of the function.
function d() {
let a = 10
var b = 20
const c = 30
}
console.log(a, b, c) // Error: a, b, and c are not defined
In Block scope
: var
can be accessed from outside of the block ({}
), but let
and const
cannot, and that's the main difference.
{
var a = 30
let b = 2000
}
console.log(a, b) // 30, Error: b is not defined