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 trialkaran Badhwar
Web Development Techdegree Graduate 18,135 PointsArray with const
How are we able to change the values in an array even if it was declared with const keyword?
Variables will throw an error, but why an array does not?
1 Answer
Steven Parker
231,248 PointsThe "const" only applies to the array itself, not the elements inside it.
You'll still get the error if you try to reassign the array:
const a = [1, 2, 3];
a[2] = 9; // this is OK
a = 999; // but this causes: "TypeError: Assignment to constant variable."
karan Badhwar
Web Development Techdegree Graduate 18,135 Pointskaran Badhwar
Web Development Techdegree Graduate 18,135 PointsBut how are we even able to change the values as well? As, when we assign the variable with const we cannot change the value, but we change specific values of arrays, but cannot change the whole value? why so?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsAs I said, "const" only protects the variable you declare with it. It does not protect anything inside that variable (like array elements or object properties).
There is a way to protect the contents also, called "freezing", but it's rather obscure. Example: