In JavaScript, the terms var and let are both used to declare variables, but var is function scoped whereas let is block scoped. As opposed to let, a variable declared with var is said to be defined throughout the entire program.

You can list out the differences in a tabular format

varlet
It has been accessible since since JavaScript first debutedis a component of ES6
There is a function scopeThere is a block scope.
Variables will be hoistedHoisted but not initialized
Difference between var and let in JavaScript

Let's use a comparison to highlight the differences.

function userDetails(username) {
  if (username) {
    console.log(salary); // undefined due to hoisting
    console.log(age); // ReferenceError: Cannot access 'age' before initialization
    let age = 30;
    var salary = 10000;
  }
  console.log(salary); //10000 (accessible to due function scope)
  console.log(age); //error: age is not defined(due to block scope)
}
userDetails("John");

Note: In the case of global scope, var and let will both function equally. For instance,

var a = 5; / 5
A will have a worldwide reach and be accessible throughout the rest of the program.

let a = 5; / 5
A will have a worldwide reach and be accessible throughout the rest of the program.


Recommended Posts

View All

Differences between JavaScript Map and Object


Discover the key dissimilarities between JavaScript Map and Object. Learn how they store data, handle key collisions, and their performance trade-offs...

What is the difference between Call, Apply and Bind


Looking to learn about the differences between Call, Apply, and Bind in JavaScript? This article breaks down the nuances of each method and provides c...

What is the purpose of the array slice method


The array slice method is a powerful tool in JavaScript used to extract a section of an array and return a new array. In this article, you'll learn ab...

4 Ways to Empty an Array in JavaScript


It is possible to empty an array in a few different ways, so let's go over every method that is available.

How do you decode or encode a URL in JavaScript?


Learn how to encode and decode URLs in JavaScript with this comprehensive guide. Avoid common mistakes and ensure data security. Read more now.