const is not constant

This blog post is brought to you by the developer of Moolabeast: Automated Expense Tracking for Android and iOS. Avoid overspending when you start tracking your expenses with Moolabeast.

Welcome back dear internet friend!

Quick little rant and opinion piece here tonight on the blog. I’ve been programming a lot lately in ReactJS and React-Native, following along with all of the various quickstart guides and tutorials related to the React tech stack, and have found myself thrust into this brave new world of JavaScript where variables do not exist. In this new world var is out, and const is in!

At least that’s how it appears looking at all of this “modern” JavaScript code I’ve been working with. I can’t remember the last time I saw the keyword var. But tonight I sort of had an epiphany: These constants don’t seem very constant to me. We’re using them just like variables!

To test this out, I fired up repl to see, can you just write over a constant whenever you feel like it? Or if you declare a new constant with the same name, is all forgiven? Well here’s what I found out. The JavaScript interpreter will get mad at you and crash if you try to write over a constant, or declare a new constant with the same name. But, if you declare a new constant inside a function you can write over it as many times as you like!

So… essentially this is what I’ve been seeing in all the modern JavaScript code I’ve been looking at. People are using constants just like variables, except the constants are always inside of a render() function or something similar so you can keep writing over it over and over and over again.

I’m sure most professional React developers know this. However, this seems pretty stupid to me. Why use a constant if you actually want a variable? I’m sure the answer has something to do with immutability! and functional programming! But I’m not buying it. const is not constant, and the emperor has no clothes.

const myConstant = "const stands for constant. It is immutable and does not change...";
console.log(myConstant);
function constIsNotReallyConstant() {
const myConstant = Math.random().toString();
console.log(myConstant);
}
for (var i = 0; i < 13; i++) {
constIsNotReallyConstant();
}
 

topherPedersen