What are the Differences Between var, let, and const?
When no keyword is used, the variable will be assigned to the global object which is the window
if we are in a browser. There are three keywords in JavaScript you can use for variable declarations. These are:
var
This is the default: it creates a function scoped variable which can be reassigned or redeclared later on.
let
This was introduced in ES6 and it is the preferred way over using var
. It creates a block-scoped variable which can be reassigned but canβt be redeclared.
const
It was introduced in ES6 along with let
. It also creates a block-scoped variable but this canβt be reassigned nor redeclared. const
should be used when you donβt want to reassign a value later on.
Itβs also good to mention that all declarations will be hoisted to the top of their scope.
var
should be avoided if can, use let
or const
instead.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: