# 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`

```js
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

```js
{
    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`

```js
{
    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

```js
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

```js
{
    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

```js
{
    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`

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

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

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

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