Difference Between let and var in JavaScript

Last updated on : Feb 24, 2025 by Shubham Srivastava

JavaScript provides multiple ways to declare variables: var, let, and const. While let and var may seem similar at first glance, they have fundamental differences in scope, hoisting, and behavior in different contexts.

In this blog, we will explore the difference between let and var, understand when to use each, and see how they behave in different scopes and functions.

DIFFERENCE BETWEEN VAR VS LET IN JAVASCRIPT - LOGICALDUNIYA.COM

What is var in JavaScript?

The var keyword was traditionally used to declare variables in JavaScript. However, it comes with certain drawbacks, particularly related to function scope and hoisting.

Example of var

The var keyword was introduced just to declare variables in JavaScript. However, it comes with certain drawbacks, particularly related to function scope and hoisting.

// LogicalDuniya example of var -

console.log('==>'+x);     // undefined
var x = 10;
console.log('==>'+x);     // 10

if (true) {
    var x = 20; 
    console.log('==>'+x); // 20
}

console.log('==>'+x);     // 20 (Value changed globally) 

Key Characteristics of var

  • Variables declared with var are function-scoped.
  • var declarations are hoisted but initialized as undefined.
  • var can be re-declared within the same scope without an error.

Let me explain characteristics of var with a diagram –


What is let in JavaScript?

The let keyword was introduced in ES6 to address the issues of var by providing block-scoped variables.

Example of let

// LogicalDuniya - Example of let -

let y = 10;
console.log(y);     // Output = 10

if (true) {
    let y = 20; 
    console.log(y); // Output = 20
}

console.log(y);     // Output = 10 (Original value retained)
 

Key Characteristics of let

  • let is block-scoped, meaning it only exists within the {} block it was declared in.
  • let cannot be re-declared in the same scope.
  • let is hoisted, but not initialized (using it before declaration causes an error).

varletconst
ScopeFunction ScopeBlock ScopeBlock Scope
HoistingHoisted as undefinedHoisted but not initializedHoisted but not initialized
Re-declarationAllowedNot allowedNot allowed
MutabilityMutableMutableImmutable

Best Practices for Usage

  • Use var only if supporting old JavaScript versions (not recommended).
  • Use let when the variable value may change in the future.
  • Use const when the variable should remain constant after assignment.

JavaScript let Vs var in Local Scope?

Local scope means that variables are accessible only within a specific function or block.

Example: Local Scope with var

// LogicalDuniya - Example of var -

function logicalFun() {
    if (true) {
        var a = 100;
    }
    console.log(a); // Output = 100 (Accessible outside the if block)
}

logicalFun();

Example: Local Scope with let

// LogicalDuniya - Example of let -

function logicalFoo() {
    if (true) {
        let b = 200;
    }
    console.log(b); // Output = ReferenceError: b is not defined
}

logicalFoo();

Key Takeaways

  • var leaks out of the block scope and it’s value is accessible outside.
  • let is truly block-scoped, meaning it only exists inside the block where it was defined.

πŸš€ Interview Tip #1
Interviewer : what would you be prefer between var and let?

You : I would always prefer to use let over var when defining variables inside blocks to prevent unintended behavior due to scope leakage.


JavaScript let Vs var in Function?

When variables are declared inside a function, their behavior depends on whether they are declared with var or let.

Example: Function Scope with var

// LogicalDuniya - Example of let -

function logicalFunctionVar() {
    var x = 10;
}
console.log(x);       // Output = Uncaught ReferenceError: x is not defined

Example: Function Scope with let

// LogicalDuniya - Example of let -

function testFunctionLet() {
    let y = 20;
}
console.log(y);       // Output = Uncaught ReferenceError: y is not defined

Key Takeaways

  • Both var and let are not accessible outside the function where they are declared.
  • This is an example where var and let behave similarly.

JavaScript let Vs var in Class?

When declaring variables inside a class, let and var behave differently in terms of scoping.

Example: Using var in Class

// LogicalDuniya - Example of var -

class LogicalExampleClass {
    constructor() {
        var x = 30;
    }
}
console.log(new LogicalExampleClass().x);       // Output = Undefined

Example: Using let in Class

// LogicalDuniya - Example of let -

class Example {
    constructor() {
        let y = 40;
    }
}
console.log(new Example().y);     // Output = Undefined (let is block-scoped)

Key Takeaways

  • Both var and let are not attached to the instance when declared inside a constructor.
  • If you want a class property, define it using this.variableName.

JavaScript let Vs var in Lambda Function?

Lambda functions (also called arrow functions) handle let and var in the same way as regular functions.

Example: Using var in Arrow Function

// LogicalDuniya - Example of var in Lambda / Arrow Function -

const LogicalVarLambda = () => {
    var a = 50;
}
console.log(a);      // Output = Uncaught ReferenceError: a is not defined

Example: Using let in Arrow Function

// LogicalDuniya - Example of let in Lambda / Arrow Function -

const testLetLambda = () => {
    let b = 60;
}
console.log(b);      // Output = Uncaught ReferenceError: a is not defined

Key Takeaways

  • Variables declared with var and let inside an arrow function do not exist outside of the function scope.

πŸš€ Interview Tip #2
Interviewer : What would you prefer between var and let in Lambda Function / Arrow Function?

You : I would always prefer let to avoid potential re-declaration issues with var.


Final Notes

In this blog, we explored the difference between let and var in JavaScript. Here’s what we learned:

  • var is function-scoped and allows re-declaration.
  • let is block-scoped and does not allow re-declaration in the same scope.
  • var variables leak out of block scopes, whereas let variables do not.
  • In functions, both var and let are scoped to the function but behave differently within blocks.
  • In classes, neither var nor let automatically becomes a class property unless attached to this.
  • In lambda functions, var and let behave the same as in regular functions.

Overall, Here is when to Use let and var

varletconst
ScopeFunction ScopeBlock ScopeBlock Scope
HoistingHoisted as undefinedHoisted but not initializedHoisted but not initialized
Re-declarationAllowedNot allowedNot allowed
MutabilityMutableMutableImmutable

By following these guidelines and understanding their differences, you can write better-structured, maintainable, and bug-free JavaScript code.

Next πŸ‘‡

  • To use hundreds of β€œFree” tools to fasten your daily development, testing and content writing tasks, visit – Tools.LogicalDuniya.com
  • To know about more tutorials of other latest technologies & concepts, visit our Tutorials page.

Happy Learning,
Shubham : )

Shubham

Shubham Srivastava

Hey there, my name is Shubham and I'm working as an SDET at a US based FinTech company. I've more than 7 years of working experience and using my knowledge - I want make this platform super helpful for those, who want to solve any software development and testing related problems. Comment your query / request or suggestion in the below section, and I'll try to respond within 24 hours. Keep improving, Keep coding !!

Recommended Posts :


0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Press ESC to close