Using const vs let (or var) when manipulating the DOM in JS


#1

I’ve been doing some tutorials on JS, and was wondering why the examples use “const” when declaring variables, as opposed to “let” or “var”.

const container = document.querySelector('#container'); // why const :O 

const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'This is the glorious text-content!';

container.appendChild(content);

#2

Hi!

I think this just a matter of preferred style. If you declare a constant (with const) instead of a variable (with let or var), it’s very easy for someone coming back to the code to see that the value is never reassigned. I find it definitely helps make it easier to quickly understand what’s happening, when I’m reading a new piece of code.

Hope this is helpful to you :slight_smile:


#4

Ah, ok! Definitely helpful, thanks for the insight! :slight_smile:


#5

The biggest reason to use const is that you’ll get a runtime error if you try to modify a constant. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const for an example.

In your case, if you accidentally modified the value of container, it could cause you a bug that would be very difficult to find. In general, anything you can do to help the computer catch your all-too-human mistakes is a good thing.


#6

Yeah this falls under the broader scope of “things the language does to help you not shoot yourself in the foot”. You have to remember, programming languages exist as they do not to help the computer, but to help the human. So as @petdance points out, this is a way to signal to humans the value should not be modified, including throwing an error if you try.