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 Arrays Multidimensional Arrays What is a Multidimensional Array?

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Array 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
Steven Parker
229,744 Points

The "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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

But 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
Steven Parker
229,744 Points

As 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:

const a = [1, 2, 3];
Object.freeze(a);
a[2] = 999;      // no error, but nothing happens
console.log(a);  // it still has [1,2,3]