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


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.textContent = 'This is the glorious text-content!';




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:


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


The biggest reason to use const is that you’ll get a runtime error if you try to modify a constant. See 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.


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.


You can think in broader system thinking: defining an architecture is to define the invariances of the system: so as to reduce the degree of freedom of it ie its complexity to what is necessary only (to meet its goal - business goal in the case of software), which means putting some constraints on elements so they cannot violate them throughout all their lifetime. Constance, Immutability, Typing,… can be viewed as means to do so.