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

Why are variables assigned as constants in their value can change?

Title

1 Answer

Shayne Laufenberg
Shayne Laufenberg
4,213 Points

You can't in javascript once you declare a constant variable inside of javascript it cannot be reassigned and it cannot not be redeclared. Constants are never meant to change they are variables that will always be the same. If you try to create a constant variable in javascript it will work very well until the moment you try to set it to some other value then it will cause an error as shown below that will not cause the second log in my console to display.

Error:

(index):49 Uncaught TypeError: Assignment to constant variable.

Test this code out for example notice I will see the first console.log since test is defined as a const correctly and the moment I try to Set it to a new value to my const it causes an error. There would be no savings in constants if they worked like every other variable, they are meant to save memory costs in your applications. Here is an example..

Example

// Define Constant Variable test //
const test = 7;

// Display Result in Console //
console.log(test);

// Set Constant Variable to 20 //
test = 20;

// Display Result in Console //
console.log(test);