In ES6, also known as ECMAScript 2015, the 'const' keyword was introduced as a way to declare variable values that are not intended to be reassigned. It behaves differently from the 'var' keyword in several ways, one of the main ones being that 'const' creates block-level scope.
Block-level scope, also known as lexical scope, refers to how a set of variables is accessible only within the block in which they're defined. Unlike 'var' which scopes variables to the nearest function block, 'const' (and 'let') restrict the scope of the declared variable to the immediate enclosing block denoted by { }. Now let's understand it with an example.
{
const example = 42;
console.log(example); // prints 42
}
console.log(example); // ReferenceError: example is not defined
In this code snippet, the constant example
is accessible within the block where it's defined between the {}
braces. However, outside of this block, example
is not defined and thus throws a ReferenceError
.
This block-level scope is particularly useful to avoid variable collisions and minimize the scope in which a variable exists, which could help prevent bugs and make your code more readable and sustainable.
It's important to note that while 'const' does create block level scope, it doesn't mean that the variable's value is immutable, it just can't be reassigned. For instance, if you define a variable as a 'const' and assign it an object, the object itself can still be altered.
const obj = {name: "John", age: 30};
console.log(obj); // {name: 'John', age: 30}
obj.age = 35;
console.log(obj); // {name: 'John', age: 35}
Remember, 'const' is not about making the value immutable, it's about making the assignment immutable. This is a common misconception about 'const'.
As a best practice, use 'const' when you have variables that you want to prevent from reassigning. It's a way to communicate the intent of your code more clearly and avoid potential errors.