Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Why are javascript const array elements mutable

It seems rather counter-intuitive for arrays declared as const to have mutable elements. What is the reasoning behind this design decision? More over if one should need a truly immutable array in JS how would that be done?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Const is not meant to make your element immutable! it only ensures that your element stays the same so you cannot assign to it a different element!

about 4 years ago · Juan Pablo Isaza Relatório

0

You can freeze the array with Object.freeze. This would make it so the elements cannot be changed.

const arr = [1, 2, 3];

arr.push(4); // arr = [1, 2, 3, 4]

const frozenArr = Object.freeze(arr);     

frozenArr.push(5); // Error: Cannot add property
frozenArr.pop(); // Error: Cannot delete property

Previous answer as it was, for reference

A const array only prevents further assignments but you are allowed to change the contents of it.

The best practice for immutable arrays is to make copies, i.e. use Array.slice() with no arguments or Array.from().

Example:

const originalArray = [1, 2, 3];

let firstNewArray = Array.from(originalArray);
firstNewArray.push(4);

let secondNewArray = originalArray.slice();
secondNewArray.push(5);

console.log(originalArray); // Output -> [1, 2, 3]
console.log(firstNewArray); // Output -> [1, 2, 3, 4]
console.log(secondNewArray); // Output -> [1, 2, 3, 5]

originalArray.push(9); // This is allowed
console.log(originalArray); // Output -> [1, 2, 3, 9]

originalArray = []; // Error: Assignment to constant variable
about 4 years ago · Juan Pablo Isaza Relatório

0

An array, number, string are all objects. They differ in the way they store values. A String are charcaters and therefore fixed if it has been declared const. An array is a construct of how multiple values are stored. This means that const sets the type imutable but not the values.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda