Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!