All caps constants in JavaScript. And requireds. And imports

slacktracer picture slacktracer · Jan 11, 2016 · Viewed 13.1k times · Source

I was used to declare constant values using all caps. Then I started using const for any value that never changes. Suddenly most things are constants. That is ok.

But the code starts to look very different.

It was talked about already: https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6

I am ok with "go ahead and const all the things!". I guess. There will be a lot of all caps around my code.

But there is more.

By this logic required stuff should be constants? I never reassigned a required. So, yes?

const GULP = require('gulp');
const ESLINT = require('gulp-eslint');

And imports are not reassignable so it should be:

import SOMETHING from 'modules/something';

Right?

I am looking for references. Best practices about constants. Someone who thought this out for longer and better than I did so far.

Or should I just choose any option and be consistent from then on?

I could not find a discussion considering at least all these points to help me organize my ideas about it. Yet.

Answer

Dwayne picture Dwayne · Jan 10, 2019

Generally speaking it is common practice to capitalize your constants. This is a convention which tells other programmers that the value is fixed. The javascript keyword const, though confusing is not a constant in that sense. I think that is where you got confused. A constant is a concept/construct. Not a primitive type within the language. You can use const to denote constants (and you should) but not every const is a constant :-) Basically a constant is a variable whose value can't or won't change during program execution. Javascripts' const variable can change it just can't be reassigned. Reassigning a value and mutating a value are two different things.

const foo = [1];
// allowed
foo.pop()
push(2);

// not allowed
foo = [];

Basically it was more or less added to give programmers a somewhat shallow immutable type. Everybody uses const because it's the safest type of variable to use if you want catch assignment errors and it is block scoped like let. And there's also a slight performance benefit for using const over let.

Something like const gulp = require('gulp'); although using const here is perfect, it is not a constant. It's a reference to a function with ever changing values.

So do keep to the convention but only when it concerns a CONSTANT. For example, if you were to build some sort of html5 video player and offer different playback speeds.

defaultPlaybackSpeed = 1; // Nothing wrong with this
doubleSpeedMultiplier = 2; // Nothing wrong with this
DEFAULT_PLAYBACK_SPEED = 1; // This though tells others this value is fixed
DOUBLE_SPEED_MULTIPLIER = 2; // Same here