Sunday, 12 January 2020

An exploration of JavaScript's variable declaration keywords (Part 3/3)

Now we come to the const keyword. Its rules are the strictest, and it should be used only in cases where the variable's assigned value is not expected to be changed.

The const keyword
It functions almost exactly like the let keyword, with one major difference - its value cannot be reassigned.

If you try this using the let or var keyword, this is legitimate and will be allowed.
let a = 5;
console.log(a);

a = 10;
console.log(a);


5
10


For const, you get an error. You can't reassign it some other value.
const a = 5;
console.log(a);

a = 10;
console.log(a);


5
Uncaught TypeError: Assignment to constant variable.


In fact, if you try to declare a variable using const, without an initial value...
const a;


...you get this error.
Uncaught SyntaxError: Missing initializer in const declaration


Needless to say, this wouldn't work either.
for (const i = 0; i < 5; i++)
{
   
}


Uncaught TypeError: Assignment to constant variable.


There is a way to get around this rule, though. Objects!

Say you declare an object variable using const. Let's call it obj, with properties a and b.
const obj = {a: 5, b: 10};

console.log(obj.a);
console.log(obj.b);


5
10


Now if you did this, there would be an error.
const obj = {a: 5, b: 10};

obj = {a: 10, b: 5};

console.log(obj.a);
console.log(obj.b);


Uncaught TypeError: Assignment to constant variable.


But if you do this, it works!
const obj = {a: 5, b: 10};

obj.a = 10;
obj.b = 5;

console.log(obj.a);
console.log(obj.b);


That's because it's the properties of obj whose values you're reassigning, not obj itself. Cool, huh?
10
5


In Conclusion

let and const introduce some rigidity into JavaScript, where it had previously been way too flexible for the comfort level of many programmers. It's possible to use var the same way too, but you'd have to be very disciplined. Maybe even extraordinarily disciplined. And when there are a lot of moving parts in your project, it may not be worth the effort.

I've been using var in JavaScript for a long time now out of sheer habit. Because I almost never use it in a way that would introduce problems, so far it hasn't given me many. But as times change, so must programming habits evolve.

Kind and constant regards,
T___T

No comments:

Post a Comment