DEV Community

Cover image for All you need to know about var, let & const in JavaScript
MAYANK TYAGI
MAYANK TYAGI

Posted on • Edited on

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

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โ˜•

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Variables can also be declared without using let, var, or const if you're not in strict mode - although in most situations this is not really best practice. Defining a function using the function keyword also technically defines a variable - with a function as its value

Collapse
 
mr_rob0t profile image
Mark Eliot

Beautifully explained in lay terms. Important read for those new to and learning JavaScript.