Issue #228 (const, Uncats, JS Utils, React Tools)11/30/17
I'm sure by now you've seen posts and examples of code that use ES6's new const statement, for declaring constants. For a succinct summary, here is a run-through of the basics regarding const.
A const cannot be changed after it's initialized. In other words, this will throw an error:
const example = 'Hello';
example = 'Bonjour';
// Error: Assignment to constant variable.
|
Also, you can't repurpose a
let or
var variable as a
const, so you'd get an error in that case too (e.g. if the "example" variable was defined using
var, then defined again using
const).
You cannot initialize a
const without defining a value. This will also throw an error:
const example;
// Error: Missing initializer in const declaration
|
Constants, like
let declarations, are block scoped. This means they aren't accessible outside of the block in which they're declared. This is one of the ways that
let statements improve on
var, and this is identical in
const.
if (true) {
var example = "Hi";
const example2 = "Hello";
}
console.log(example); // "Hi"
console.log(example2); // Error: example2 is not defined
|
As shown in the example above, the
const declaration is not hoisted so it's not accessible outside the
if block. And note that you can use
const to initialize a variable in a
for loop, as long as the loop doesn't modify the value of the
const.
Although a
const declaration can't be changed after it's initialized, an object declared as a
const can be modified. For example, this is valid:
const example = {
one: 'Hello'
};
console.log(example.one); // "Hello"
example.one = 'Hi';
console.log(example.one); // "Hi"
|
Using the above code, it's the value of "example" that can't be altered, not the values of properties within the object itself.
Finally, as a best practice recommendation: Use
const as the default, unless you know that the value is intended to change; then use
let. This is different from what most developers might have assumed, which is to use
let to replace
var. You should use
const to replace
var as long as you know the value is not intended to change.
More info on
const on MDN and lots of credit to
Nicolas Zakas' Understanding ECMAScript 6 for his great coverage of this and other ES6 topics.
Now on to this week's tools!