Can anyone explain why here a = [] ? 1 : 2 a will be equal to 1 and here b = [] == true ? 1 : 2 b will be equal to 2
Can anyone explain why here a = [] ? 1 : 2 a will
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A very similar case is handled in Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b').
In short:
When you have a single value that is evaluated in a boolean context, it is passed to
ToBooleanto be converted to a boolean value.If you compare values with
==though, the algorithm in section 11.9.3 of the ECMAScript specification takes place. In this algorithm, both operands are converted to either strings or numbers and these values are compared.More detailed explanation
a = [] ? 1 : 2The condition is converted to a boolean by calling
ToBoolean(GetValue(lref)). Now I assume that for objects,GetValuejust returns the object itself and all objects evaluate totrue.Since arrays are just objects, the result of this expression is
1.b = [] == true ? 1 : 2As already said, quite some type conversion is going on here.
First,
trueis converted to a number:falseis converted to0andtrueis converted to1.So we have
Then step 9 applies:
That means
[]is converted to a primitive value (string or number). If you follow theToPrimitivefunction (and section 8.12.8), you’ll find out that arrays are converted to strings, by concatenating their elements with,. Since an empty array as no elements, the result is an empty string.So we end up with
Then step 5 applies:
An empty string is converted to
0, hence0 == 1isfalseand the conditional operator returns2.