3

Why does node.js allow a module (or an object) specified as a constant to be changed?

For example, this is allowed:

const EXPRESS = require('express');
EXPRESS.someProperty = 'some value';

But this is not:

const MYCONST = '123';
MYCONST = '456';
Azevedo
  • 2,059
  • 6
  • 34
  • 52

3 Answers3

7

const means that you cannot change the reference itself, not what the reference points to.

const a = { name: 'tom' };

// you cannot change the reference (point a to something else)
a = 5; // this is an error

// but you can change the value stored at that reference with no problem
a.name = 'bob';
nem035
  • 34,790
  • 6
  • 87
  • 99
4

const does not make the object to become immutable thus you can change the object itself but you can not assign another object to that reference

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const

Dmitry Matveev
  • 5,320
  • 1
  • 32
  • 43
2

From the docs:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.

This isn't node-specific, it is part of the Javascript spec. The reference EXPRESS is the constant, and when you declare using const you are not allowed to reassign the reference.

const EXPRESS = require('express');
EXPRESS = 'something else';

would also fail

Rob M.
  • 35,491
  • 6
  • 51
  • 50