Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript gotcha: empty list to boolean conversion

Tags:

javascript

Why both

 [] == false

and

![] == false

are true?

like image 457
luntain Avatar asked Oct 07 '09 20:10

luntain


People also ask

Is Empty list Falsy in JavaScript?

Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.

Is empty string Falsy?

Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just use not string.

How do I convert numbers to boolean in typescript?

Use the Boolean object to convert a value to a boolean in Typescript, e.g. Boolean(someValue) . When used as a function, the Boolean object converts the passed in value to a boolean - true if the value is truthy and false if it's a falsy value. Copied!

Why is an empty array true?

arrays are objects, objects are truthy. just ask for array. length, if not zero, it will be truthy. when you explicitly convert to Boolean, the array turns into an empty string first, then the empty string turns into false.


1 Answers

The === operator is your friend. Never use the == operator; it will bite you, as you can see.

like image 148
Anthony Mills Avatar answered Oct 16 '22 01:10

Anthony Mills