All you need to know about var, let & const in JavaScript

MAYANK TYAGI - Aug 20 '21 - - Dev Community

In JavaScript a variable can be defined using the keywords var, let, or const.

Before we can understand how var, let, and const differ, we need to understand a computer science-y concept called scope.
Scope essentially means where these variables are available for use.

Global Scope

Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.

Function Scope

Variables declared Locally (inside a function) have Function Scope.
Local variables can only be accessed from inside the function where they are declared.

Block Scope

A block of code is the code between curly braces in JavaScript.
Variables declared inside a block {} have block scope.

Variables declared with the var keyword cannot have Block Scope.

var

var declarations are globally scoped or function/locally scoped.
The scope is global when a var variable is declared outside a function.
var is function scoped when it is declared within a function.

image

variables declared with var keyword can be re-declared like this
image

or their value can be updated like this
image

let

let is now preferred for variable declaration. It's no surprise as it comes as an improvement to var declarations. It also solves the problem with var. Let's consider why this is so.
let is block-scoped, so a variable declared in a block with let is only available for use within that block.

image

variables declared with let keyword cannot be re-declared it will throw error like this
image

let variables can be updated within its scope like this
image

const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.
Like let declarations, const declarations can only be accessed within the block they were declared.

image

But variable declared with const can neither be re-declared nor re-assigned

image

image

Thanks for reading.

"Don't miss out" Follow my Social handles👉
Subscribe my YouTube channel😊
Instagram😊 || Twitter😊

If you find this helpful and want to support💲 Buy Me Coffee☕

. . . . . . . . .
Terabox Video Player