DEV Community

Akinsanya Toluwanimi
Akinsanya Toluwanimi

Posted on

What is the difference between var, let and const in JavaScript?

Var, let and const are used to declare a variables in JavaScript. A variable is a container that holds a value.
DIFFERENCE BETWEEN VAR, LET AND CONST.

  1. Var has a function scope: this mean the variable is accessible throughout the entire functions regardless of the block it's in. Let has a blocked scope: this means that the variable is only accessible within the block it's declared it. This is the same with Const.
  2. Var allows re-assignment of the same variable multiple times within the same scope Let does not allow re-assignment of the same variable within the same scope Const does not allow re-assignment of the same variable within the same scope

Why is it recommended to const for JavaScript

  1. In const a variable declared cannot be re-assigned.This helps prevent unintended changes to the variable assigned.
  2. Prevents accidental re-assignment.

Top comments (1)

Collapse
 
stephengade profile image
Stephen Gbolagade

Hello @akinsanya_toluwanimi_e409

Allow me to correct a few things here:

Let allows reassignment but does not allow redeclaration in the same scope

For Instance:

let a = 7
a = 10 // you have reassign 10 to a which is allowed
Enter fullscreen mode Exit fullscreen mode

but you cannot say:

let a = 7
let a = 10 // this is redeclaration and it's not allowed.
Enter fullscreen mode Exit fullscreen mode

Tips:

  • Break your sentence into small small paragraphs
  • Write code to explain so readers can virtualize what you're saying
  • Use Grammarly to proof-read