Declaring JavaScript Variables: var, let, and const

·

3 min read

In this tutorial, we are going to get the answer about some question which comes to our mind while learning JS which confuse us.

What are Variables?

Variable means anything that can vary. Before ECMA2015, JavaScript variables were solely declared using the var keyword.

var.PNG

Above we are declaring x, y, and z which means that these variables exist. If we try to find typeOf any of the above we will get undefined.

Declaring Variable in ES2015

In ES2015 or above we can declare variables using:

  • var
  • let
  • const

Using var

JavaScript uses reserved keyword var to declare a variable. ... You can assign a value to a variable using equal to (=) operator when you declare it or before using it.

var1.PNG

After the first declaration of a variable in the global scope, subsequent declarations of a variable name using var is possible.

var2.PNG

Note: Always name variable in camelcase.

Using let

The variable type let shares a lot of similarities with var but unlike var has scope constraints. let is constrained to whichever scope it is declared in. Its declaration and assignment are similar to var

let.PNG Unlike var, variables cannot be re-declared using let, trying to do that will throw a Syntax error: Identifier has already been declared

Using Const

It is a variable type (not really, but you’ll find out now) assigned to data whose value cannot and will not be changed throughout the script.

const.PNG Use const when you are sure a variable will not be redeclared.

Capture.PNG Note: A variable declared with const MUST be initialized.

Which to use

When declaring variables, it is good practice to avoid using var. Always lean towards let or const based on the following rules.

  • Use let when we will be changing the value of the variable
  • Use const when you are sure that variable won't change

Conclusion

In this, we learn the difference between var, let, and const.

Resources

Thank you