Hey future SDEs! Are you gearing up for your dream tech placements in 2026? Thinking about that ₹12LPA+ package at a buzzing Bangalore or Hyderabad startup? If JavaScript is on your radar – and it absolutely should be for roles at companies like TCS, Infosys, and Google India – then understanding `var`, `let`, and `const` is non-negotiable.
When I started learning JavaScript, I kept seeing the same advice repeated everywhere: “Use `let` and `const`, don't use `var`.” It felt like a coding commandment. But why? What exactly did JavaScript ‘change its mind’ about, and more importantly, how does this impact your code quality and, yes, your placement interviews?
Let’s dive deep into the evolution of variable declaration in JavaScript, dissect their nuances, and arm you with the knowledge to impress any interviewer.
The OG: `var` (Before ES6)
Before 2015, `var` was the only way to declare variables in JavaScript. It served its purpose, but it came with a few quirks that often led to unexpected bugs, especially in larger codebases. Think of `var` as JavaScript’s 'wild west' era.
Scope with `var`
- **Function-Scoped:** Variables declared with `var` are scoped to the nearest function. If declared outside any function, they become globally scoped. This means they are not block-scoped (i.e., not limited to `if` blocks, `for` loops, etc.).
```javascript function exampleVarScope() { if (true) { var x = 10; // x is function-scoped, not block-scoped } console.log(x); // Output: 10 (accessible outside the if block) } exampleVarScope(); // console.log(x); // Error if not global, x is not defined outside function ```
Hoisting with `var`
- **Hoisted to the Top of its Scope:** Variables declared with `var` are 'hoisted' to the top of their function or global scope during the compilation phase. Their *declarations* are moved, but *initializations* stay in place. If you try to access a `var` before its actual declaration, it will be `undefined` instead of throwing an error.
```javascript console.log(myVar); // Output: undefined var myVar = 20; console.log(myVar); // Output: 20 ```
Redeclaration and Reassignment with `var`
- **Allowed:** You can easily redeclare and reassign `var` variables without any error.
```javascript var y = 30; var y = 40; // Redeclared, no error console.log(y); // Output: 40
y = 50; // Reassigned console.log(y); // Output: 50 ```
These seemingly flexible features of `var` often led to bugs, especially when variables with the same name were unknowingly declared in different parts of a large application.
The Revolution: `let` and `const` (ES6+)
With the release of ECMAScript 2015 (ES6), JavaScript introduced `let` and `const` to address the shortcomings of `var` and provide developers with more control and predictability. This was JavaScript's way of maturing and becoming a more robust language for complex applications.
`let`: The Block-Scoped Variable
`let` is your go-to for variables whose values might change. It’s a significant improvement over `var`.
- **Block-Scoped:** Unlike `var`, `let` variables are scoped to the nearest enclosing block (`{}`). This means they are confined to `if` statements, `for` loops, `while` loops, and other blocks, preventing unintended access or modification from outside.
```javascript function exampleLetScope() { if (true) { let z = 60; // z is block-scoped console.log(z); // Output: 60 } // console.log(z); // Error: z is not defined (accessible only inside the if block) } exampleLetScope(); ```
- **No Redeclaration, Allows Reassignment:** You cannot redeclare a `let` variable within the same scope, which helps prevent naming conflicts and bugs. However, you can reassign its value.
```javascript let msg = "Hello"; // let msg = "Hi"; // Error: Identifier 'msg' has already been declared msg = "Hola"; // Reassignment is fine console.log(msg); // Output: Hola ```
- **Temporal Dead Zone (TDZ):** While `let` variables are hoisted, they are not initialized with `undefined`. Instead, they are placed in a 'Temporal Dead Zone' from the start of their block until their declaration. Accessing them before their declaration results in a `ReferenceError`.
```javascript // console.log(count); // ReferenceError: Cannot access 'count' before initialization let count = 100; console.log(count); // Output: 100 ```
`const`: The Constant Companion
`const` is designed for variables whose values are *intended* to remain constant throughout their lifetime. Use it when you know a value shouldn't change.
- **Block-Scoped:** Just like `let`, `const` variables are block-scoped.
```javascript if (true) { const PI = 3.14; console.log(PI); // Output: 3.14 } // console.log(PI); // Error: PI is not defined ```
- **No Redeclaration, No Reassignment:** This is `const`'s defining feature. Once a `const` variable is declared and initialized, its value cannot be reassigned.
```javascript const API_KEY = "mysecretkey"; // API_KEY = "anotherkey"; // Error: Assignment to constant variable. // const API_KEY = "newkey"; // Error: Identifier 'API_KEY' has already been declared ```
- **Important Note for Objects/Arrays:** While `const` prevents reassigning the variable itself, it *does not* make the *content* of an object or array immutable. You can still modify properties of an object or elements of an array declared with `const`.
```javascript const user = { name: "Alice", age: 25 }; user.age = 26; // This is perfectly fine! console.log(user); // Output: { name: 'Alice', age: 26 }
// user = { name: "Bob" }; // Error: Assignment to constant variable. ```
- **Temporal Dead Zone (TDZ):** `const` also has a TDZ, behaving like `let` in this regard.
```javascript // console.log(MAX_ATTEMPTS); // ReferenceError: Cannot access 'MAX_ATTEMPTS' before initialization const MAX_ATTEMPTS = 5; ```
Why JavaScript Evolved: The “Why” Behind the Change
The introduction of `let` and `const` wasn't just for fun; it was a crucial step in modernizing JavaScript and making it a more reliable language for enterprise-level applications and complex front-end frameworks.
- **Reducing Bugs & Improving Readability:** `var`'s function-scoping and hoisting behaviors often led to tricky bugs that were hard to trace. `let` and `const` (with their block-scoping and TDZ) provide more predictable behavior, making code easier to reason about, debug, and maintain.
- **Preventing Global Scope Pollution:** `var` variables declared outside functions become global, potentially overwriting existing global variables. `let` and `const` encourage better encapsulation, limiting variables to their necessary scope.
- **Clarity of Intent:** `const` explicitly signals that a variable's value should not change, making code more self-documenting. This helps other developers (and your future self!) understand the code's design.
- **Alignment with Other Languages:** Many other programming languages (like Java, C++, Python) use block-scoping. The introduction of `let` and `const` brought JavaScript more in line with these industry standards.
Which One to Use When? DevLingo’s Best Practices for Your Interview!
This is often asked in `TCS NQT`, `Infosys SP`, and `Google India SDE-1` interviews! Here’s the widely accepted best practice:
1. **Prefer `const` by default:** If you declare a variable and don't anticipate its value changing, use `const`. This signals immutability and makes your code safer and clearer. Remember, it doesn't make objects/arrays immutable, just the variable binding itself. 2. **Use `let` when reassignment is necessary:** If you know a variable's value will need to change (e.g., in a loop counter, a state variable, or a value that's updated based on user input), then `let` is the appropriate choice. 3. **Avoid `var`:** Unless you're working with very old legacy codebases that you cannot refactor, there's rarely a good reason to use `var` in modern JavaScript development. Sticking to `let` and `const` is a hallmark of a professional JS developer.
Mastering `var`, `let`, `const` for Your 2026 Placement Prep
Understanding `var`, `let`, and `const` isn't just about memorizing definitions; it's about grasping the 'why' behind JavaScript's evolution. This depth of understanding is what separates a good candidate from a great one in competitive interviews for top SDE roles.
Companies are looking for developers who write clean, maintainable, and predictable code. By demonstrating a solid understanding of these core concepts, you're signaling to recruiters that you grasp modern JavaScript best practices, a crucial skill for that coveted ₹12LPA+ role at any leading startup or tech giant.
Ready to put your knowledge to the test? Head over to DevLingo and practice interactive challenges focused on `var`, `let`, and `const`. Our gamified modules are designed to solidify your understanding and boost your confidence for the toughest technical rounds!
**Happy Coding, Future Tech Leaders!**
Frequently Asked Questions
How does this appear in interviews?
Interviewers often present code snippets involving `var`, `let`, and `const` and ask you to predict the output or identify errors. They might also ask 'When would you use `let` versus `const`?' or 'Explain the Temporal Dead Zone.' Demonstrating the 'why' behind their differences and knowing common pitfalls (like `var`'s function scope) is key.
What is a common mistake developers make when using `const`?
A very common mistake is assuming `const` makes an object or array entirely immutable. While `const` prevents you from reassigning the variable itself (e.g., `const arr = [1]; arr = [2];` is an error), it does *not* prevent you from modifying the *contents* of the object or array (e.g., `const arr = [1]; arr.push(2);` is perfectly valid). This distinction is crucial for interviews.
