1st Part:
Because When you are adding two arrays, everything works as expected:
[] + [] //output:''
Adding an array and an object also conforms to our expectations:
[] + {}
output:'[object Object]'
{} + {}
in JavaScript is NaN
?
and this is unexpected result so what is the reason behind this?
2nd part:
In string comparison without prefix 0, 3 is greater than 12:
"3" > "12"
: true
With padding, everything works correctly:
"03" > "12"
: false
Is prefix 0 compulsory for string comparision?What is the reason for adding prefix 0 ?
So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
{} + {}
is interpreted as the empty block {}
followed by the expression + {}
. {}
has no numerical value, so it yields NaN
. If you force it to be evaluated as an expression like ({} + {})
, you'll get [object Object][object Object]
.
They're strings, so they'll be compared lexicographically. If you want to compare them as numbers, parse them first using parseInt
or parseFloat
.
the first part
1-
when you add two arrays you take the primitive value for each and arrays can be converted to strings like the following [1,2,3,4].toString() //=> 1,2,3,4
so the two emty arrays generates to empty strings and the concatenation between them generates empty string.
2-
when for the second when you add empty string with object, you are converting the object to string and as shown the string value of an object is [object Object]
3-
when you add two objects, in the way shown you are just converting an object to number by the +
check this question
Part Two
String compare is made letter by letter from left to right and as soon as there is a deference the return value is determined ignoring the string length like the following
"3" > "12"
"3" in ASCII is bigger than "1" so the return is TRUE
"03" > "12"
"0" in ASCII is smaller than "1" so the return is False
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