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

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)

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

5 JavaScript console method you should be aware of

JavaScript includes several fantastic console methods that are less commonly used yet really useful.

What are the Different Data Types in JavaScript

A web scripting language is called JavaScript. It contains its own data types, much like any other computer language. The type of data that a variable...

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...

What is prototype and prototype chaining in JavaScript

This article explains the concept of prototype and prototype chaining in JavaScript. Learn how prototypes work, how they are used to create inheritanc...

Top 10 ES6 Features Every JavaScript Developer Must Know

The specification for JavaScript implementation is provided by ES6. Learn about its recently added ES6 features that make writing JavaScript easier!