JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

const vs. var? Not sure what the difference is...they both seem to serve the exact same function.

const vs. var? Not sure what the difference is...they both seem to serve the exact same function.

1 Answer

andren
andren
28,367 Points

const creates a constant. A constant is a type of variable that cannot have its value reassigned after it is assigned.

Take this code:

const example = 20; // Set example to 20
example = 10; // Change value of example to 10

That would be perfectly valid if var was used, but with const it produces a TypeError. Because once example was assigned a value it can never be assigned a different one.

One caveat worth mentioning is that while you can't reassign the value of a constant it does not prevent you from making changes to something that is assigned to it. For example if you have an object assigned, changing the value of one of its properties will work even when const is used. const just prevents you from assigning a different thing to the constant.