Declare variables in JavaScript

3 JS Methods Of Declaration Explained

Praveena Thavarajah
TheLeanProgrammer
2 min readApr 17, 2021

--

JavaScript is a scripting language. It has 3 methods to declare variables as,

Let's have a look at a brief explanation of each of the methods, and ways to declare the variables.

Var keyword is there from the earlier version of the JavaScript. The keywords let and const used from ES6 which was introduced in 2015.

1.let

· Mutable (the variable can be changed at any time)

· Declare empty variables and reassign them when-ever needed.

· Global scope -The variable can be accessed inside a function as well as outside a function.

How to use let.

2.var

· Mutable

· Function scope -The variable is declared inside a function and used inside the function. This variable cannot be used outside the function.

How to use var.

3.const

  • The variables which are assigned and not willing to change (immutable variable).
  • If a variable once declared with const keyword and if we try to change it, errors will be thrown.
Error
  • This is the best way to declare variables to prevent errors(bugs) when coding for programs.

When coding for a website we have to use the same variable several times. Sometimes spelling mistakes may happen when assigning the value. As const prevents reassigning values, it throws errors and prevents the possibility to get errors.

How to use const.

Conclusion

There are three ways to declare variables in JavaScript as let, var and const. So it is important to know how and where to use the appropriate keywords in the program.

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer

--

--