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

246
Visualizações
Why array + array returns a string?

Why does summing 2 arrays joins everything in a string, concatenating the first and last values:

  let array = [1, 2]

  let array2 = [3, 4]

  let array3 = array + array2

  console.log(array3) // 1,23,4
about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

That's just how JavaScript works. Both are objects, there's not a defined thing for + between an Array and an Array, so it does the default thing of converting to String and concatenating them (still as a String).

Use the Array.prototype.concat method to acheive your goal.

let array = [1, 2]

let array2 = [3, 4]

let array3 = array.concat(array2);

console.log(array3) // [1, 2, 3, 4]

Alternatively, you can use the spread operator:

let array = [1, 2]

let array2 = [3, 4]

let array3 = [...array, ...array2];

console.log(array3) // [1, 2, 3, 4]

about 4 years ago · Santiago Gelvez Relatório

0

Because the + operator acts diffently according to the type of the given operands.

  • If both operands are numbers, then a sum if performed.
  • If one of the operand is not number, then both operands are transformed into string (using .toString) and concatenated.

In your example you may notice that:

array + array2 == array.toString() + array2.toString()

For further information you may read the docs and the spec

about 4 years ago · Santiago Gelvez Relatório

0

Javascript tries to be smart and figure out what you are trying to do. An addition sign implies adding two strings, so Javascript goes ahead and converts the arrays to strings first for you. How nice, right?

What you want to do is implement the concat method:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2)
about 4 years ago · Santiago Gelvez 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