var and let in JavaScript
π§ 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
| Feature | var | let |
| Scope | Function-scoped | Block-scoped |
| Hoisting | Yes (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,
numberis declared usingvar, 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
counteris declared inside a block, it's available outside too due tovar'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
varallows 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 β
userNameis accessible globally in its scope.
π Example 2: Block Scope Limitation
{
let country = 'India';
console.log(country); // Output: India
}
console.log(country); // β ReferenceError
countryis not accessible outside its block β this is the block-scoping behavior oflet.
π Example 3: Redeclaration Not Allowed
{
let city = 'Mumbai';
console.log(city); // Output: Mumbai
let city = 'Pune'; // β SyntaxError: Identifier 'city' has already been declared
}
letdoes 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
letinside the methodcaptureInput()to ensure variableinputValuehas 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,
letis used for theinputAgevariable 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.

