Difference between var, let and const in JavaScript

Function scope vs Block scope in JavaScript

In this article, we will cover differences between var, let and const.

In ES6, we get two new ways to define variables let and const, we used var to define variables before ES6.

Let's understand function scope and block scope

The code between cruly braces {} is refer to block of code

Function Scope

Visibility of variable is limited to function in function scope.

function fnScope() {
  var str = 'Function Scope';
  console.log(str); // 'Function Scope'

console.log(str); // ReferenceError: str is not defined

Block Scope

Visibility of variable is limited to block in block scope.

if(true) {
  var a = 'TheBitOps';
  let b = 'javascript';
  const c = 'Development';
  console.log(a); // 'TheBitOps'
  console.log(a); // 'javascript'
  console.log(a); // 'Development'

console.log(a); // 'TheBitOps'
console.log(b); // ReferenceError: b is not defined
console.log(c); // ReferenceError: c is not defined

Here you can see clearly variable a visibility is not limited to if block while variable b and c is limited to if block

So var has function scope and let/const have block scope

Var variables can be redeclared and updated

    var str = "hey handsome";
    var str = "say Hello to him";

    // and 
    var str = "hey handsome";
    str = "say Hello to him";

let variables can't be redeclared and but we can update them

    let str = "hey handsome";
    let str = "say Hello to him"; // error: Identifier 'str' has already been declared

    // and code below will work fine and update variable value
    let str = "hey handsome";
    str = "say Hello to him";

const variables can't be redeclared or updated

    const str = "hey handsome";
    str = "say Hello to him"; // error: Assignment to constant variable.

    // not this
    const str = "hey handsome";
    const str = "say Hello to him";

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *