What's the difference between var, let & const? Let's find out..

Scope, Hoisting, declaration and initialization

What's the difference between var, let & const? Let's find out..

With ES2015(ES6) alot of new features were introduced, and out of them let and const also came into picture.

Let's start with var keyword

Scope of var

Scope basically means from where we can access the variable. var is gloabal and function scoped.

Global scope => written outside the function and is accessible throughout the window.

Function scope => written inside the function and is accessible only in the function.

var helloWorld = "Hello World";
function sayHello() {
  var hello = "Hello";
}
console.log(helloWorld); // Prints Hello World
console.log(hello); // Gives ReferenceError: hello is not defined

var variables can be redeclared and updated

var name = "Thomas Shelby";
var name = "Alfie Solomons";
// This is also possible
name = "Arthur Shelby";

Hoisting of var

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. - MDN Web Docs

Hoisting allows functions to be safely used in code before they are declared.

console.log(name); // undefined
var name; // declaration
name = "Polly" // initialization
var name = "Campbell"; // both

Problems with var

It is not blocked scope.

for (var i = 0; i < 2; i++){
  console.log(i) // Prints 0,1
}
console.log("this",i); // this 2

Moving on to Let and const

Let and const both blocked scope

for (let i = 0; i < 2; i++){
  console.log(i) // Print 0, 1
}
console.log("this",i); // Gives ReferenceError: i is not defined

Let can be updated but not redeclared

let name = "Hello World";
console.log(name); // Hello World
name = "Hello Updated";
console.log(name); // Hello Updated
let name = "something"; // SyntaxError: Identifier name has already been declared

Hoisting of Let and var

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

console.log(hello); // Gives Reference error : Cannot access hello 
let hello = "Hi"; 

console.log(name); // ReferenceError:Cannot access name before initialization
const name = "Billi";

const cannot be updated and redeclared

const name = "Adam";
name = "John"; // TypeError Assignment to constant variable.

Although, we can update objects inside a const

const obj = {
  name : "Adam",
  age : "10"
}
console.log(obj.name); // Prints Adam
obj.name = "Eve";
console.log(obj.name); // Prints Eve

That was it, Thank you for reading :)