15

when we define an array as constant in javascript does it mean that array cannot shrink or enlarge and have a constant size, or, does it mean that all the elements in an array are constant and you cannot change their value.

handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState({squares: squares}); } 

in the above code.

0

1 Answer 1

26

Declaring a variable as const only means that you cannot assign a new value to that variable once a value has been assigned:

const array = []; array = []; // Not allowed: assignment to constant variable 

Declaring an array as const has no bearing on what you can do with the contents of the actual array:

const array = []; array.push("something"); // Allowed: add value to array array[0] = "or other"; // Allowed: replace value in array array.length = 0; // Allowed: change array size 
Sign up to request clarification or add additional context in comments.

1 Comment

Addendum: const keyword is simply used to declare a constant reference to an object. This reference cannot be made to refer to something else but the object referred to can still be mutated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.