var
provides functional scoping but not block scoping. var allow to log the variable without declaring it though it shows undefined.let
provides functional scoping as well as block scoping.const
provies functional scoping as well as block scoping but you cannot reassign value to aconst
type variable.
let
and const
will not allow you the log the variable without declaring it.
Keyword | Scope | Hoisting | Can Be Reassigned | Can Be Redeclared |
---|---|---|---|---|
var | Function scope | Yes | Yes | Yes |
let | Block scope | No | Yes | No |
const | Block scope | No | No | No |
If we try to use a variable before it has been declared and initialized, it will return undefined
.
console.log(x);
var x = 5;
Output: undefined
.
However, if we try to remove var
keyword, so now we are no longer declaring the variable, only initializing it. It will return a ReferenceError
and stop the execution of the script.
console.log(x);
x = 5;
Output: ReferenceError: x is not defined
.
This is because of Hoisting
. In Javascript, variable and function declarations are moved to the top of their scope.
// The code we wrote
console.log(x);
var x = 10;
// How JavaScript interpreted it
var x;
console.log(x);
x = 10;
Since only the declaration is hoisted, not the initialization, the value returned is undefined
.
Javascript saved x
to memory before the execution of the script. Since it was called before it was defined, the result is undefined
and not 10.