Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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,558 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.