Javascript var, let and const

People always got confused about how to use var, let and const when declare a variable, especially for Javascript beginners. Today we are going to talk about their differences from various perspectives:

Scope

Var can be used for declaring globally scoped variable and function scoped variable.

var a = 1
function example(){
var b = 2
console.log(b) // 2
}
console.log(a) // 1

let and const are block scoped, var is not block scoped.

Block scope: “The block is delimited by a pair of braces (“curly brackets”)”. Such as if…else…statement and loops.

You can see that we can still access c but not d and E.

let and const can still be used to declare global variables, they just do not create properties of the window object when declared globally (in the top-most scope).

Declare and Update

var variables can be update and re-declared within its scope:

var a = 1
var b = 2
var b = 3 // re-declare
function test1(){
a = 10
console.log(a)
}
console.log(a) // 1
test1() // 10
console.log(a) // 10
console.log(b) // 3

let variables can be updated but cannot be re-declared

let a = 1
let b = 2
let b = 3 // SyntaxError: Identifier 'b' has already been declared
function test1(){
a = 10
console.log(a)
}
console.log(a) // 1
test1() // 10
console.log(a) // 10

const variables can neither be updated nor re-declared

const A = 1
const B = 2
const B = 3 // SyntaxError: Identifier 'b' has already been declared
function test1(){
A = 10 //TypeError: Assignment to constant variable.
console.log(A)
}

The const keyword makes a variable itself immutable, not its assigned content. If you use const to declare an object, the object itself can still be altered.

const C = {
firstName: "Amy",
gender: "F"
}
//cannot do://C = { // TypeError: Assignment to constant variable.
// firstName: "Bobby",
// gender: "F"
//}
//can do:C.firstName = "Bobby"
console.log(C) // { firstName: 'Bobby', gender: 'F' }

Hoisting

“Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

All of them are hoisted to the top of their scope. var variables are initialized with undefined, let and const variables are not initialized. So when you try to access variable before declaration, var variable will return undefined, but let and const variables will return reference error:

console.log(a) // undefined
var a = 1
console.log(b) // ReferenceError: Cannot access 'b' before initialization
let b = 2
console.log(C) // ReferenceError: Cannot access 'C' before initialization
const C = 3

Initialization

var and let can declare variables without assigning initial values to them, const must be initialized during declaration.

var a 
console.log(a) //undefined
let b
console.log(b) // undefined
const C //SyntaxError: Missing initializer in const declaration
console.log(C)

Resources: