DEV Community

Gurjot-Sidhu
Gurjot-Sidhu

Posted on

Var, let, const and everything in between

Var,Let and Const. All 3 are different ways to declare variables in javascript. They are different from one another in ways that change the way how they are used. Let me explain...

VAR was the go to declaration for a long time until ES6 came out in June of 2015. One of the new additions was let and const.

The first major difference occurs in the Scope of these variables.

Scope - determines the accessibility of variables

  • Global Scope - Available throughout the whole window

  • Function Scope - Available ONLY in that function {}

  • Block Scope - Available ONLY within its {}

Var can be declared to have global and function scope.

var intro = "hello";// available globally

function end2020pls (){
    var outro = "bye"; // only available here
}

console.log(intro) // works
console.log(outro) // error outro not defined

Let can be declared within block scope.

function end2020pls (){
     let newintro = "say Hi";
     console.log(newintro); // say Hi
}

console.log(newintro)// error newintro not defined
  • However, the same let variable can exist in different scopes
let intro = "hello";// outside

function end2020pls(){
     let intro = "not today";// inside
     console.log(intro); // not today
}

console.log(intro); // hello

Const can be declared within block scope

function end2020pls(){
     const newoutro = "see you later, alligator";
     console.log(newoutro);// see you later, alligator 
}

console.log(newoutro);// error newoutro is not defined

Updating and Redeclaring

Var can be updated and redeclared.

var intro = "hello"; 
var intro = "goodbye"; // works
intro = "suh dude"; // works

Let can be updated but CANNOT be redeclared.

let intro = "hello";
let intro = "goodbye"; // error intro has already been declared

Const Cannot be updated or redeclared.

const intro = "hello";
intro = "yo"; // error Assignment to constant variable
const intro = "yo"; // error intro has already been declared

Objects declared with Const cannot be updated or redeclared its properties can.

const person = { 
     name: "bob";,
     age: "99";
}

person.age = 67; //works

Hoisting - a javascript mechanism where variables and function declarations are moved to the top of code execution

Var gets hoisted but is undefined

So this
console.log(intro);
var intro = "hello";
is actually
var intro;
console.log(intro); // intro is undefined
intro = "hello";

Let gets hoisted but is not initialized.

function end2020pls(){
     console.log(x)//error ReferenceError x is not defined
     let x = 2;
}

Const gets hoisted but is not initialized.

function end2020pls(){
     console.log(x) // error ReferenceError x is not defined
     const x = 2;
}

Thats all for now, feel free to reach out if I am missing something ;)

Top comments (0)