Why can .pop() method change the structure of array that was defined as const variable?


#1

Arrays and Functions

Hello! Why can .pop() method change the structure of array that was defined as const variable ?


FAQ: Arrays - Arrays and Functions
FAQ: Arrays - Arrays and Functions
#2

Because only the variable name and structure type are constant. The elements themselves are mutable. What this means though is that we cannot clear the array with,

concept = []
        ^

TypeError: Assignment to constant variable.

like we can in the case of var or let. We must pop or shift until the array is empty to clear it.

while (concept.length) {
  console.log(`'${concept.pop()}' taken off the array.`);
}
console.log(concept);
'MUTATED' taken off the array.
'be' taken off the array.
'can' taken off the array.
'arrays' taken off the array.
[]

or,

while (concept.length) {
  console.log(`'${concept.shift()}' taken off the array.`);
}
console.log(concept);
'arrays' taken off the array.
'can' taken off the array.
'be' taken off the array.
'MUTATED' taken off the array.
[]

#3

Thanks a lot for clarifying!