Declaring Variables the Right Way in JavaScript
Using var, let and const in JavaScript, and how each differs in their behavior
Variable declaration is one of the basic concepts you can learn when you start learning a new programming language. JavaScript has three different keywords (var
, let
, and const
) that you can use to declare a variable, and they each have their characteristics and behaviors.
In this article, you will see:
- How to declare variables using each keyword
- The scope of the declared variable using each keyword in different scenarios.
- Can we reassign and redeclare variables for each type of declaration?
- A Brief discussion on variable and function hoisting when we declare variables using the
var
keyword. - Which one you should and should not use, based on the different scenarios.
So let’s get started about the details on each one of them.
var
A variable declared using var
has function scope which means its scope is throughout the function in which it resides and if the same declared outside any function, has a global scope and is accessible throughout the code.
Function scope example
As shown, the variable declared inside a function can only be accessed inside it
Global Scope example
As shown, a variable not inside any function is accessible anywhere
Note: A variable declared using
var
can be redeclared, so there is a chance that you may override the variable accidentally, here the typeslet
andconst
comes into play, we will discuss them in the latter…