My learning diary


I thought consolidating constants was evil. Just two or three dozens of them were enough to become a huge headache for me. In Java, this practice is frowned upon. In JavaScript, it seemed alright.

The answer which received the bounty recommended the following:

// Warning: This answer was written in 2014.
module.exports = Object.freeze({
  MY_CONSTANT: 'some value',
  ANOTHER_CONSTANT: 'another value'

It was my first time encountering Object.freeze, so I went to google for the difference between Object.freeze and const. TL;DR: Object.freeze prevents further writing to the keys and their values (with exceptions). Nested keys are exempt from this.

If you scroll a little further down the thread about sharing JavaScript constants, you will see:

const FOO = 'bar';

module.exports = {

That led to my final answer:

export const TOTAL_MONTHS_PER_YEAR = 12;

// import { TOTAL_MONTHS_PER_YEAR } from './constants';

This method of managing constants is not reviewed by my team yet. Will keep you posted, but it will be some time before I request for another review…

Relevant posts