Var Let and Const in Javascript. What is the difference?

The right way to declare variables in JavaScript

But, What is wrong with var?

The Scope

function scope(){
var name = "javascript tutorials"
console.log(name)
}
console.log(name) //Error: name not defined
if(true){
var name = "javascript tutorials"
}
console.log(name) //javascript tutorials
if(true){
let name = "javascript tutorials"
}
console.log(name) //Error: name not defined
if(true){
const name = "javascript tutorials"
}
console.log(name) //Error: name not defined
var result = 0....if(true){
var result = 1 //accidentally re-declared
}
console.log(result) //result changed to 1
let result = 0....if(true){
let result = 1 //accidentally re-declared
}
console.log(result) //result remains 0

The Declaration and Reassignment

var myNumber = 45...var myNumber = 100  //accidently redeclared...console.log(result)   //result changes to 100 (expected 45)
let myNumber = 45...let myNumber = 100  //Error:'myNumber' has already // been declared...console.log(result)   //45
let myNumber = 45...myNumber = 100  //variable reassiged...console.log(result)   //100

Now, what’s with const?

const myNumber = 45...myNumber = 100  //Error: Assignment to constant variable...console.log(result)

Now, which one should be used where?

Photo by Darren Nunis on Unsplash

Technical blogger | YouTube instructor | JavaScript Lover | MERN stack engineer | social innovator and of course a Coder