Let vs Const vs Var
Introduction
In JavaScript, let
, const
, and var
are used to declare a variable.
Each is slightly different and has different scope rules that can affect how they
are managed in your code.
In this article we'll explore the differences and appropriate use cases for let
, const
,
and var
, but before let's check out what scope
and hositing
are.
Scope in JS
In-depth guide about scope Link->
Scope in JavaScript refers to the access of variables and functions in different parts of the code. It determines where variables and functions can be accessed or modified. JavaScript has three types of scope:
- Global Scope: Variables declared outside any function are in the global scope and can be accessed from anywhere in the code
- Function Scope: Variables declared in a function using var are function scoped, meaning they are accessible only within that function.
- Block Scope: Variables declared with
let
andconst
are block-scoped, meaning they are only accessible within the block (if, for loop etc.) they are declared in.
Hoisiting
In-depth guide about hoisting Link->
Hoisting is moving declarations to the top of their scope before code execution. This applies to both variable and function declarations.
Variables declared with var
are hoisted and initialized with undefined.
let
and const
declarations are hoisted but not initialized.
Function declarations are hoisted entirely, meaning you can call them before they appear in the code.
3 ways do declare a variable
var
Not used nowadays, var
is function-scoped, meaning it is accessible within the function it is declared.
Also, var
variables are hoisted and initialized with undefined
.
let
let
is block-scoped and was introduced in ES6.
It allows for the declaration of variables that are limited to the block scope.
const
const
is also block scoped and introduced in ES6. It is used to declare variables that should not be reassigned.
Differences between var, let and const
Scope
var
: function scopelet
,const
: block scope
Re-declaration
var
: can be re-declaredlet
,const
: cannot be re-declared
Hoisting
var
: hoisted, initialized with undefinedlet
,const
: hoisted, not initialized
Re-assignment
var
,let
: can be re-assignedconst
: cannot be re-assigned
Best practices
- Don't use
var
- Use either
const
orlet
(be consistent)
I personally write code in such way that in 99% of cases I use const
. I rearely
use let
, only if I really have to. However, it's a personal preference.