6 Ways to Declare a Variable in JavaScript
var, let, const, function, class, import, and more
It is used to say that in JavaScript variables can be declared with var
, let
and const
, but if you think about it, the function declaration, the class declaration, and the import
statement are also ways to declare variables. This article looks at all of them.
var
var
allows to declares variables that can be reassigned. Nonetheless, it has a few problems:
- Variables can be used before declaration. The declarations are hoisted to the top of their scope. When used before declaration variables have the value of
undefined
. - Variables can be redeclared in the same sope. This approach basically reassigns the existing variable.
- It does not have black scope.
Here is an example.
var x = 1;
var
declarations have become obsolete.
let
let
declares a variable that can be reassigned. Variables declared with let
cannot be used before declarations and cannot be redeclared in the same scope. It can have block scope. It basically fixes the problems of the var
declaration.