DEV Community

alternativeboy
alternativeboy

Posted on

Var vs Const vs Let what is different ?

TL;DR The differences between these three are Scope, Declaration, Update Value and Re-declaration

Contents

These three are the way to declare variables in Javascript.

Before ES6 in Javascript, You can declare variables by using var, But the problem is var scope is global, It has a chance to occur Name collision.

Const and Let introduce in ES6, They come to solve to problem of var because of Block scope.

They are used in different scenarios, Const is used when we don't want to change the value of variables and Let we can change the value of variables depending on the event.

I think some of you are a little bit confusing because it has a lot of information, Let me show you the table to compare the differences between these three types of variables declaration. It will be easy to understand and apply to your implementations.

Declaration Type Scope Declaration Update value Re-declare
var globally, function Without initialize Yes Yes
const block Need initialize No No
let block Without initialize Yes No

I will explain what happens above giving a comparison table. First, start from Scope.

Scope

Scope determines the accessibility (visibility) of variables. Or the level of accessibility and visibility of variables.

Contains 3 levels

  • Block scope
  • Function scope
  • Global scope

before ES6 come, They have only Function scope and Global scope.

Declaration

You need to initialize the value of variables when you declare if you used const, But no need for var and let.

Update value

If we need to change the value of a variable, We need to use var or let only.

Tips

You have noticed each declaration has something different, You need to consider by a situation when to use var, const, or let. My suggestion is to use const or let for reduced the scope problem especially global scope from var, It will make a Name collision.

If something's wrong, incomplete or you want to share the experience. Please let me know in the comment.
Thank you for taking the time to read this😘.

Discussion (0)