6

I am a bit confused by the behavior of Array.map function here:

var arr = ['one', 'two', 'three'];
var result = '';
result += arr.map(function(elm) {
    return elm;
});

// 'one,two,three'

How does it automatically join the returned results with a , ?

Note: This only happens if I concatenate the returned result in a string.

Avijit Gupta
  • 5,676
  • 3
  • 20
  • 35

3 Answers3

12

Array.map did nothing to your array.

You basically did this

'' + ['one', 'two', 'three']

Which calls the toString() method of an array, whose default behaviour is to join(',') the array.

Prashanth Chandra
  • 2,672
  • 3
  • 24
  • 42
5
var arr = ['one', 'two', 'three'];
var result = '';
var r = arr.map(function(elm) {
    result = result + ' ' + elm;
    return elm;
});
alert('r-> ' + r);
alert('result-> ' + result);

It is because the arr.map function is returning after processing each element in array and not for individual elements as you are expecting to append to 'result' variable. If you wish to concatenate values to 'result' variable, you should do so inside the map function for each element instead. And as Sirko said, the commas are coming from the toString() method. Check the above code on jsfiddle here: http://jsfiddle.net/qt3nryLq/

Reference to Array.map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Abhijit Annaldas
  • 669
  • 4
  • 12
2

The commas stem from the toString() method of Array and not the map() function!

var arr = ['one', 'two', 'three'];

arr.toString(); // 'one,two,three'

var result = '';
result += arr.map(function(elm) {
    return elm;
});

result.toString(); // 'one,two,three'
Sirko
  • 72,589
  • 19
  • 149
  • 183