# The Difference Between var, let and const
1- var variable can be redeclared and updated.
1a) example of redeclare a var variable.
var greeter = "hey hi";
var greeter = "say Hello";
1b) example of updated var variable.
var greeter = "hey hi";
greeter = "say Hello";
2-let variable can be updated but not redeclared.
2a) example of redeclare a let variable.
let points = 50;
let points = 60;
In the console I get an error:
'points' has already been declared
2b) example of updated let variable.
let points = 50;
points = 60;
// In console:
points
// Returns:
60
3- const variable cannot be updated or re-declared.
3a) example of updated const variable.
const greeting = "say Hi";
greeting = "say Hello instead";
// error: Assignment to constant variable.
3b) example of redeclare a const variable.
const greeting = "say Hi";
const greeting = "say Hello";
// error: Identifier 'greeting' has already been declared.
1- var declarations are globally scoped or function scoped/locally scoped
var greeter = "hey hi";
function newFunction() {
var hello = "hello";
console.log(hello);
}
console.log(hello); //print error
Here, greeter is globally scoped because it exists outside a function while hello is function scoped. So we cannot access the variable hello outside of a function. So if we do this:
console.log(hello); // error: hello is not defined
2c) let are block scoped.
A variable declared in a block with let is only available for use within that block.
example:--
let greeting = "say Hi";
let times = 4;
if (times > 3) {
let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
3c) const are block scoped.
Problem with var:--
var greeter = "hey hi";
var times = 4;
if (times > 3) {
var greeter = "say Hello instead";
}
console.log(greeter) // "say Hello instead"
it becomes a problem when you do not realize that a variable greeter has already been defined before.
If you have used greeter in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why let and const are necessary.
Hoisting of var, let and const:--
They are all hoisted to the top of their scope. But while var variables are initialized with undefined, let and const variables are not initialized.