let, const, and var are three keywords for declaring variables in Javascript.
1. let
Scope:
Block-scoped.
- A variable declared with let is only accessible within the block (code enclosed in curly braces {}) where it's declared.
- This is crucial for preventing accidental variable reassignment from outer scopes.
Reassignment:
- Allowed. You can change the value stored in a let variable after it's declared.
Temporal Dead Zone (TDZ):
- Variables declared with let exist in a TDZ before their declaration, meaning you cannot access or modify them until they are fully declared.
This is in contrast to var and const hoisting behavior.
Example:
if (true) {
let foo = 10; // Accessible only within this block
console.log(foo); // Output: 10
}
console.log(foo); // ReferenceError: foo is not defined (TDZ)
2. const:
Scope:
- Block-scoped, similar to let.
Reassignment:
- Not allowed. Once you assign a value to a const variable, you cannot modify it later.
- This helps prevent unintended changes and potential bugs.
Hoisting:
- Not hoisted. const declarations are not moved to the top of their scope like var declarations. They must be declared before use.
Example:
const foo = 111; // Declaring a constant value
foo = 333; // TypeError: Assignment to constant variable
3. var:
Scope: Function-scoped.
- A variable declared with var is accessible throughout the function where it's declared, even within nested blocks.
- This can be problematic for large codebases as it can lead to unintended side effects and variable naming conflicts.
Reassignment:
- Allowed, like let.
Hoisting:
- Hoisted. var declarations are moved to the top of their scope (function or global scope) during compilation, making them accessible before their declaration.
- This can be confusing and lead to unexpected behavior if not used carefully.
Example:
for (var i = 0; i < 3; i++) {
console.log(i); // Output: 0, 1, 2
}console.log(i); // Output: 3 (accessible even outside the loop due to hoisting)
Best Practices:
- In modern JavaScript development, it's strongly recommended to use const and let instead of var due to their improved scoping behavior and reduced risk of unintended variable reassignment.
- Prefer const for variables that should remain constant throughout the code, and use let when you need to reassign values.
Note:
const id=6767676
let name='abcd'
var pwd="886876"
city="Bangalore"
1.id=10 //not allowed
2.name="bgbg"
3.pwd="78787"
4.city="hyd"
Prefer not to use var because there was an issue with the block-scoped and functional scope, we use let instead of var.
0 Comments:
Post a Comment