const declarations

const Declarations – Undertstanding ES6

No TL;DR Required 🙂

const Declarations

So the next easy introduction to some ES6 properties are const declarations. const declarations are equivalent to var DONTCHANGEME = "foo" in ES5. When I say equivalent I mean in idea not behavior.

The var syntax and variables created with var can be assigned and re-assigned at any time. In ES6 the “read-only” nature of const declarations is respected and enforced

1
2
3
const a = 4;  //4

a = 5;  //a is read-only

const declarations must also have explicit declarations. This means the const declarations must be intiliazed with a value. For example:

1
2
3
4
5
6
7
let a;
var b;
const c;

console.log(a) //undefined
console.log(b) //undefined
console.log(v) //const variables must have an initializer

The following paragraph is from the book You Don’t Know Javascript: ES6 & Beyond

const declarations are not a restriction on the value itself, but on the variable’s assignment of that value. In other words, the value is not frozen or immutable because of const, just the assignment of it. If the value is complex, such as an object or array, the contents of the value can still be modified:

1
2
3
4
5
6
7
{
    const a = [1,2,3];
    a.push( 4 );
    console.log( a );       // [1,2,3,4]

    a = 42;                 // TypeError!
}

The a variable doesn’t actually hold a constant array; rather, it holds a constant reference to the array. The array itself is freely mutable.

One last note about const declarations. Some people are of the opinion that it is a best practice to declare all variables as const declarations and only promote them to let declarations as needed. It is said that this is faster for the JS engine because it knows the variable wont change so there is less tracking. However, because probably less than 1% of the variable I declare are constant I don’t think it is worth the effort.

Pro Tip: Learn ES6

Read “You Don’t Know JavaScript: ES6 & Beyond” for free online! Click Here.

Leave a Reply

Your email address will not be published. Required fields are marked *