When we delve into the world of JavaScript, one of the first things we encounter is how to declare variables. In JavaScript, there are three ways to do this: using var, let, or const. Each of these keywords has different attributes that make them unique and useful in different scenarios.
Here's a brief comparison of var, let, and const:
Property | var | let | const |
---|---|---|---|
Scope | Function scope | Block scope | Block scope |
Hoisting | Yes | Yes, but not initialized | Yes, but not initialized |
Re-declarable | Yes | No | No |
Re-assignable | Yes | Yes | No |
In JavaScript, scope determines the accessibility or visibility of variables, functions, and objects in some particular code region. It controls the visibility and accessibility of variables and other such items in areas of your code.
The var keyword is function scoped, meaning the variable declared with var is restricted to the function within which it is declared.
function exampleFunction() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
let, introduced in ES6, is block-scoped. A block is chunk of code bounded by {}. A variable declared with the keyword let in a block, can only be used within that block.
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
Variables declared with the keyword const maintain constant values. const declarations share some similarities with let declarations.
const number = 42;
try {
number = 99;
} catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
In conclusion, var, let and const each have their unique uses and are all essential tools in a JavaScript developer's toolkit. While var can be function-scoped and re-declared, let is block-scoped and not re-declarable. const, on the other hand, is block-scoped, not re-declarable and, additionally, not re-assignable.