We have given an expression [1, 2] + [3, 4], and the result of this expression is “1,23,4”. In this article, we will know why this weird result we get.
Example :
=> [1,2] + [3,4] => "1,23,4" => [1, 2, 3, 4] + [9, 8] => "1, 2, 3, 49, 8" => [4] + [] => "4" => [] + [] => ""
Before knowing the reason first we understand the addition operator ( + ) and its result with different data types. As we know there are 6 built-in data types in javascript Number, String, Object, Boolean, Undefined and null. And the result of the addition of different kinds of data types is different.
For example: The undefined + undefined => number, undefined + object => String etc.
In the table below all the result of the addition is given
undefined | null | boolean | number | String | Object | |
undefined | number | number | number | number | string | string |
null | number | number | number | number | string | string |
boolean | number | number | number | number | string | string |
number | number | number | number | number | string | string |
String | string | string | string | string | string | string |
Object | string | string | string | string | string | string |
Example: The example is the way to got that table, by this simple JavaScript program.
Javascript
<script> let arr1 = [undefined, null , 1, "" , {}]; let arr2 = [undefined, null , 1, "" , {}]; for ( var i = 0; i < arr1.length; i++) { arr2.map((item) => { console.log( typeof (arr1[i] + item)); }); console.log( "\n\n" ); } </script> |
Output : In the above program, there are two arrays in which all 6 data type values are provided. We add every item of arr1 with every item of arr2 and printing the type of the result. That’s how we created the above table.
Now come to our problem [1,2] + [3,4], here we are adding two arrays we know that the type of array is an object, so according to the above table when we add two objects then we get the result of string type. JavaScript converts the two arrays into a string and then concatenate them. Here both array becomes “1,2” and “3,4” and when the two strings concatenate then we get “1,23,4”