DEV Community

Cover image for Var, Let, and Const in JavaScript
Thushara Thiwanka
Thushara Thiwanka

Posted on • Edited on

Var, Let, and Const in JavaScript

In JavaScript, var, let, and const are three ways of creating variables. Here, we will talk about the scope and difference between these three ways.

Bit of history on variable declaration

At the beginning of JavaScript, there was one way to declare a variable and, that is using the var keyword. Then let and const are introduced in ES6 but couldn't use it right away. Now, all the major browsers compatible with the let and const syntax, and most of the developers use let and const nowadays.

Var

Variables declared using var keyword scoped to the current execution context. This means If they are inside a function we only can access them inside the function. and If they are not they are part of the global scope which we can access anywhere. look at the example below to better understanding.

Alt Text

Here, Mango is scoped to function scope and Apple belongs to the global scope. If we try to access a global variable it is possible. but if we try to access a function scoped variable it is not possible. look at another example below.

Alt Text

One of the issues with using the var keyword is they can be redeclared inside the same scope. This will brings up some serious issues if we declare another variable using the same name inside the same scope, the new variable will replace the old one. var can be updated as well.

Alt Text

And another issue with var is these variables are not block-scoped which means if we have conditions statements those are not scoped to that statement but to the entire function or to the global scope.

Alt Text

Let

This is the improved version of var declarations. Variables declaration using this way eliminates all the issues that we discussed earlier. let creates variables that are block-scoped. Also, they can not be redeclared and can be updated. The below example shows it is the best choice to use let than var.

Alt Text

Check out the below example to understand more about the behavior of let in the block scope.

Alt Text

Const

Const variables are cannot be updated or redeclared. This way is used to declare constants. Same as the let declarations const declarations are block-scoped. Unlike var and let, If we are using const to declare a variable that must be initialized.

Alt Text

If we use const when object creating we can still update properties inside that object. Refer to the below example for better understanding.

Alt Text

I personally prefer to use let and const over var and use const to declare constant variables and always use let to declare variables if it is not a constant.

Top comments (0)