var, let and const in Javascript
var, let and const are the three keywords which is used before variables.
var keyword is used before let and const came into picture.
var is function-scoped. This means whenever a variable is created with var in a function, it will only exist within the function, for example 👇
var a = 1;
function example(){
a=2;
console.log(a);
}
example();
In the above example var a is global scoped which is access everywhere . However, the reverse is not true. If we declare a variable inside a function, we cannot use it outside the function. if we use variable ( declared inside the function) outside . What will happen ?
See below example :)
function example(){
var a=2;
console.log(a);
}
console.log(a); //ReferenceError: a is not defined
example();
var keyword also allows for reassignment. Here's what i mean
var a=10;
function reassign(){
a=30;
}
console.log(a);//10
reassign();
console.log(a);//30
a=40;
console.log(a);//40
//output :10 30 40
we assign a variable how many times as we want . var can redeclare a variable , Here's what i mean
var a=10;
var a=20;
console.log(a); //20
//output:20
redeclaration of a variable which is a bad idea, when we want some variable immutable var keywords fails to give.
var keyword no longer used , instead of var we have let and const keywords.
Let's see let and const keywords
let
let
is a block scoped, This means whenever a variable is created with let
, it will only exist within its block.
what’s a block?
A block in JavaScript is anything within a pair of curly braces.
Just like var
, variables declared with let
can be reassigned to other values, but they cannot be redeclared
Here in the below example let keyword is not allowing to redeclare same variable. if we redeclare a same variable it give error. here's what i mean
let a=10;
let a=20;
console.log(a); //SyntaxError: Identifier 'a' has already been declared
Here is the another example
function example(){
let a=20;
console.log(a);
}
console.log(a); //ReferenceError: a is not defined
example();
In above example we declared a variable a
in function we can only access the variable inside the function , if we try to access an variable which is inside the function it will give an error.
const
const is also a block scoped , same as let but we cannot redeclare a variable once we declared . This is the special about the const
Here are the example for const
const p=10;
p=20;
console.log(p); //TypeError: Assignment to constant variable.