Let, Var and Const – What's the Differences?
Thi?u Quang Khoa
?Performance Tuning at Wecommit Vi?t Name | Oracle Database | Software Engineering Major at FPT University | 7.0 IETLS?
The var Keyword
The var keyword has been around since the inception of JavaScript and is known for its function-scoped nature. Unlike block-scoped variables, var variables are either globally scoped if declared outside any function or function-scoped if declared inside a function.
Example of var:
In the example above, the variable topic declared with var inside the if block is accessible outside the block but still within the same function. This is because var does not adhere to block scope; instead, it is scoped to the nearest function.
The Problem with var
The lack of block scope can lead to unexpected behavior, particularly in loops and conditional statements. Consider the following example:
One might expect this code to log 0, 1, 2, 3, and 4 to the console. However, it prints 5 five times. This is because var is function-scoped, and by the time the setTimeout callback executes, the loop has completed, leaving i with a value of 5.
The let Keyword
To address the shortcomings of var, ES6 introduced let, which is block-scoped. Variables declared with let are confined to the block in which they are declared, and they are not accessible outside of that block.
领英推荐
Example of let:
In this example, the variable course is declared inside a block using let. Attempting to access course outside the block results in a ReferenceError because let is block-scoped.
let in Loops
One of the most common uses of let is in loops, where it helps avoid the pitfalls associated with var:
This time, the code logs 0, 1, 2, 3, and 4 as expected. Each iteration of the loop creates a new block scope for i, ensuring that the correct value is logged by the setTimeout callback.
The const Keyword
The const keyword, like let, is block-scoped. However, it has an additional constraint: variables declared with const cannot be reassigned after their initial assignment. This makes const ideal for declaring constants or values that should not change.
Example of const:
In this example, the variable course is declared with const, and any attempt to reassign it results in a TypeError. However, it's important to note that const does not make the value itself immutable—only the binding is immutable.
Example with Objects:
Here, although person is declared with const, we can still modify the properties of the object because const only prevents reassignment of the variable itself, not its contents.
Conclusion
Understanding the differences between var, let, and const is crucial for writing clean and bug-free JavaScript code.