Reputation: 41
I always used let for var declaration until now instead of const, cuz with let you can modify the value of the variable, thing that with const you can't do(at least this was what I knew), so why use const? thanks to everyone!!
Upvotes: 0
Views: 912
Reputation: 119
const and let have block scope whereas var has functional scope. const can be used define constant value such as PI. const can also be used to define function using fat arrow.
Upvotes: 0
Reputation: 1560
Using const can be helpful to avoid immutability to some extent. But obviously it does not guarantee that.
I'd recommend you use const whenever you can, if not then let.
Most people out there get away using let/const
but there might be some rare cases where you'd want to employ var
.
Note, const allows you to modify, just not reassign.
Example:
const arr = ['foo'];
// valid operation
arr.push('bar');
// valid operation
arr[0] = 'Mike';
console.log(arr);
try {
const arr = [];
arr = ['foo'];
} catch (e) {
console.warn(e.message);
}
Upvotes: 1