var array = [1,2,4];
array+1 //gives '1,2,41'.
Can anyone explain this behaviour?
To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .
In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise. let's look at the syntax… const allEqual = arr => arr.
Can anyone explain this behaviour?
This answer attempts to explain this behavior from the point of view of spec.
As per spec, during the run-time evaluation of +
, both expressions (left and right) are converted to their primitive values.
- Let lprim be ToPrimitive(lval).
- Let rprim be ToPrimitive(rval).
toPrimitive tries to pass hint:number
(since invoked during arithmetic evaluation) to OrdinaryToPrimitive
- If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».- Else,
b. Let methodNames be «"valueOf", "toString"». //this gets invoked
Since one of the values were casted to string via 4a) above, string concatenation takes place.
Hence
[1,2,4] + 1
=> [1,2,4].toString() + "1"
=> "1,2,4" + "1"
=> (finally) "1,2,41"
Array is casted to string - then concatenated with integer value which is also casted to string.
When you use the +
sign with a declared javascipt object (var array
), even if one of the elements is a number, it doesn't perform an arithmetic addition operation - it concatenates the values as two strings.
In your example, your array [1,2,4]
is being casted into a string with a value of 1,2,4
. So 1,2,4
concatenated with 1
is 1,2,41
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With