Difference between let, var and const in Javascript
- Get link
- X
- Other Apps
In JavaScript, `var`, `let`, and `const` are used to declare variables, but they have some differences in terms of scoping, reassignment, and hoisting. Here's a breakdown of their key differences:
1. `var`:
- Variables declared with `var` have function scope or global scope (if declared outside any function).
- They can be reassigned and redeclared within the same scope without generating errors.
- `var` variables are hoisted, meaning they are moved to the top of their scope during the compilation phase, allowing them to be accessed before they are declared.
- Example:
function example() {
var x = 10;
if (true) {
var x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 20
}
example();
In this example, the `x` variable is declared with `var` inside the function. When the `if` block is executed, a new assignment to `x` changes its value within the entire function scope.
2. `let`:
- Variables declared with `let` have block scope, meaning they are limited to the block in which they are defined (e.g., inside loops or conditionals).
- They can be reassigned but not redeclared within the same scope.
- `let` variables are not hoisted, so they cannot be accessed before they are declared.
- Example:
function example() {
let x = 10;
if (true) {
let x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
example();
```
In this example, the `x` variable is declared with `let`. The `let` keyword allows the `x` variable in the `if` block to have a separate scope from the `x` variable in the outer scope.
3. `const`:
- Variables declared with `const` also have block scope.
- They must be assigned a value when declared and cannot be reassigned or redeclared within the same scope.
- `const` variables are not hoisted and follow the same scoping rules as `let` variables.
- `const` is used for values that are intended to be constant and not changed throughout the program.
- Example:
function example() {
const x = 10;
if (true) {
const x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
example();
In this example, the `x` variable is declared with `const`. It cannot be reassigned or redeclared within the same scope, preserving its initial value.
It is generally recommended to use `let` or `const` over `var` as they provide block scoping and stricter reassignment rules, which help avoid unintended side effects and make code more maintainable. Use `let` when you need to reassign a variable and use `const` for variables that should not be changed.
- Get link
- X
- Other Apps
Comments
Post a Comment