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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With