
Let and const in Node.js #
Let is introduced recently and it’s new way of defining variable. If it’s new then there must be some old of doing that, yes there is.
The old way is using var
for declaring the variable. The is some logical error when you use var, i.e Hoisting.
Features #
Feature | Const | Let | var |
---|---|---|---|
Allow re-declaring | ❌ | ❌ | ✅ |
Hoisted | ❌ | ❌ | ✅ |
global scope | ❌ | ❌ | ✅ |
initial value required | ✅ | ❌ | ❌ |
can’t update value | ✅ | ❌ | ❌ |
In the previous lecture, I talked about Hoisting. In this lecture I will focus on other things which is global scope.
Let #
Let allow us to declare the variable once only in a scope and it does not make it available in global scope
.
> var first = 09;
undefined
> global.first
9
> let second = 9
undefined
> global.second
undefined
>
const #
Let allow us to declare the variable once only in a scope and it does not make it available in global scope
.
> const pi = 3.1;
undefined
> pi = 3.14
Uncaught TypeError: Assignment to constant variable.
>
At the time of writing this, I was using Node.js v12.16.3.