Skip to main content

Command Palette

Search for a command to run...

var and let in JavaScript

Published
β€’4 min readβ€’View as Markdown

🧠 Difference Between var and let in JavaScript β€” with Real LWC Examples

In JavaScript, both var and let are used to declare variables. However, they differ significantly in terms of scope, redeclaration behavior, and best practices for modern development. Understanding these differences is crucial, especially when working in frameworks like Lightning Web Components (LWC), where clean and predictable code is essential.


πŸ” var vs let: A Deep Dive

🎯 Key Differences at a Glance

Featurevarlet
ScopeFunction-scopedBlock-scoped
HoistingYes (initialized as undefined)Yes (but not initialized)
Redeclaration Allowedβœ… Yes❌ No
Temporal Dead Zone❌ Noβœ… Yes
Best Practice?❌ Outdatedβœ… Recommended

πŸ“˜ var Keyword: Examples and Behavior

πŸ“Œ Example 1: Function Scope with var

var number = 100;
{
    console.log(number);     // Output: 100
}
console.log(number);         // Output: 100

Here, number is declared using var, so it’s accessible inside and outside the block β€” because it’s function-scoped.


πŸ“Œ Example 2: Declaration Inside Block

{
    var counter = 50;
    console.log(counter);   // Output: 50
}
console.log(counter);       // Output: 50

Again, even though counter is declared inside a block, it's available outside too due to var's function-scoping.


πŸ“Œ Example 3: Redeclaring with var

{
    var score = 90;
    console.log(score);     // Output: 90
    var score = 95;         // Redeclaration allowed
}
console.log(score);         // Output: 95

var allows redeclaration, which can lead to bugs and unpredictable behavior.


πŸ“˜ let Keyword: Examples and Behavior

πŸ“Œ Example 1: Global Declaration

let userName = 'Alex';
{
    console.log(userName);  // Output: Alex
}
console.log(userName);      // Output: Alex

Declared outside the block β€” userName is accessible globally in its scope.


πŸ“Œ Example 2: Block Scope Limitation

{
    let country = 'India';
    console.log(country);   // Output: India
}
console.log(country);       // ❌ ReferenceError

country is not accessible outside its block β€” this is the block-scoping behavior of let.


πŸ“Œ Example 3: Redeclaration Not Allowed

{
    let city = 'Mumbai';
    console.log(city);      // Output: Mumbai
    let city = 'Pune';      // ❌ SyntaxError: Identifier 'city' has already been declared
}

let does not allow variable redeclaration in the same scope β€” this improves safety.


⚑ Real-Time Example in LWC: Handling Input with let

πŸ“‚ Component Name: userInputHandler

πŸ“„ userInputHandler.html

<template>
    <lightning-card title="User Input Form">

        <div class="slds-p-horizontal_x-small">
            <lightning-input type="text" 
                             label="First Name" 
                             name="firstInput" 
                             placeholder="Enter First Name"
                             onchange={captureInput}>
            </lightning-input>

            <lightning-input type="text" 
                             label="Last Name" 
                             name="secondInput" 
                             placeholder="Enter Last Name"
                             onchange={captureInput}>
            </lightning-input>

            <br/>
            <center>
                <lightning-button variant="brand" 
                                  label="Submit" 
                                  title="Submit Info" 
                                  onclick={submitInfo} 
                                  class="slds-m-left_x-small">
                </lightning-button>
            </center>
        </div>
    </lightning-card>
</template>

πŸ“˜ userInputHandler.js

import { LightningElement } from 'lwc';

export default class UserInputHandler extends LightningElement {

    firstName;
    lastName;

    captureInput(event) {
        let inputValue = event.target.value;

        if(event.target.name === 'firstInput') {
            this.firstName = inputValue;
        } else if(event.target.name === 'secondInput') {
            this.lastName = inputValue;
        }
    }

    submitInfo() {
        alert(`First Name: ${this.firstName}`);
        alert(`Last Name: ${this.lastName}`);
    }
}

Here, we use let inside the method captureInput() to ensure variable inputValue has local block scope, preventing accidental overrides.


πŸ€– Conditional Logic Example in LWC: Voting Eligibility

πŸ“‚ Component Name: voterEligibilityCheck

πŸ“„ voterEligibilityCheck.html

<template>
    <lightning-card title="Voter Eligibility">

        <div class="slds-p-horizontal_x-small">
            <lightning-input type="number" 
                             label="Enter Age" 
                             placeholder="Enter Age..."
                             onchange={checkEligibility}>
            </lightning-input>

            <template lwc:if={isEligible}>
                You are eligible for voting.
            </template>

            <template lwc:elseif={isNotEligible}>
                You are not eligible for voting.
            </template>

            <template lwc:else>
                Please enter a valid age.
            </template>
        </div>
    </lightning-card>
</template>

πŸ“˜ voterEligibilityCheck.js

import { LightningElement } from 'lwc';

export default class VoterEligibilityCheck extends LightningElement {

    age;
    isEligible = false;
    isNotEligible = false;

    checkEligibility(event) {
        let inputAge = parseInt(event.target.value, 10);
        this.age = inputAge;

        if (!inputAge || inputAge <= 0) {
            this.isEligible = false;
            this.isNotEligible = false;
        } else if (inputAge < 18) {
            this.isEligible = false;
            this.isNotEligible = true;
        } else if (inputAge >= 18 && inputAge <= 100) {
            this.isEligible = true;
            this.isNotEligible = false;
        } else {
            this.isEligible = false;
            this.isNotEligible = false;
        }
    }
}

Here again, let is used for the inputAge variable because we want its usage limited to the block of code where it’s used.


βœ…

In modern JavaScript (including in LWC), it is strongly recommended to use let instead of var. While var is still valid, it can introduce subtle bugs due to its function-scoping and redeclaration behavior.

Using let provides:

  • Safer variable handling

  • Better scoping practices

  • Cleaner, more predictable code β€” especially in reactive frameworks like Lightning Web Components.

1 views

More from this blog

B

BlackBUC

29 posts