1
if([]==true) //evalutes as false

//when i check empty array with true, if evaluating [] as false so it if condition return false

if([]) //evalutes as true

//when i check empty array alone, if evaluating [] as true so it if condition return true

why it is evaluating like that?

thanks

2 Answers 2

5

Based on abstract equality comparison algorithm your first code will be evaluated like below,

step 1 : ToNumber([]) == true

step 2 : ToPrimitive([]) == true

(ToNumber() will call ToPrimitve() when the passed argument is an object)

step 3 : "" == true

step 4 : 0 == true

step 5 : false == true

step 6 : false

And in your second case, [] is a truthy value, so if([]) will be evaluated to true always, here [] will not be converted as a primitive. Abstract equality comparison algorithm comes into play when you use == operator.

Another better example would be,

var x = [] || "hello";
console.log(x); // [] 

Since [] is a truthy value, x would be set with [] not "hello"

Sign up to request clarification or add additional context in comments.

2 Comments

ToPrimitive will be called if type of y is either string or number. This is basically taking last point 10. since it is satisfying neither of first 9 conditions. You gave the correct part of the spec though. +1
i dont understand one thing...why it calls ToNumber method when we are comparing with boolean?
0

When you use only a variable as the condition (without comparison operators), Javascript will cast it to Boolean using the Boolean() function:

http://www.w3schools.com/js/js_booleans.asp

In your case, Boolean([]) = true so it returned as true.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.