4

I can't figure out why we can change a DOM element even if we are declaring it as a constant.If we are not changing it so what are we really doing? thank you in advance.

const button = document.getElementsByTagName('button')[0];
const domElement = document.getElementsByTagName('div')[0];
button.addEventListener('click', e => {domElement.innerText = "how can I be modified even I am const?"});
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>DOM Example</title>
    
</head>
<body>
    <div>change me</div>
    <button>Change a DOM element </button>
</body>
</html>
Firas Omrane
  • 894
  • 1
  • 14
  • 21
  • 3
    When a const is an object, the object itself isn't re-assignable, but the properties on that object can change. MDN does a great job of explaining this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const – Chris Riebschlager Jan 16 '18 at 23:15

1 Answers1

9

const only prevents you from changing what object the variable reference points to. It does nothing to stop you from modifying the object itself.

This would be illegal:

const x = 5;
x = 4; // ERROR

const x = { a: 1 };
x = { b: 2 }; // ERROR

But this is fine:

const x = { a: 1 };
x.a = 5;
casieber
  • 7,264
  • 2
  • 20
  • 34
  • Do you know if it is considered good practice to declare an object with `const` (as opposed to `let`) all the while intending on changing its properties, as with your last example? – reformed Feb 21 '19 at 16:12
  • 2
    You'll find differing opinions about "good practice" and immutability, but in my opinion yes, it is entirely good practice. In JS `const` doesn't mean (or imply) that the entire object being referenced is necessarily immutable, only that the reference itself is immutable. So if you don't intent to mutate what object the variable is pointing to, then go ahead and make it `const`, even if you do intend on mutating the object itself. – casieber Feb 21 '19 at 18:28
  • Great, thanks for the insight! – reformed Feb 22 '19 at 05:52