Beware JavaScript's Boolean() Function

I recently wrote the following line of code:

newsletterPopupEnabled = Boolean($("#newsletterPopupEnabled").val());

The point of this was to correctly parse a string of "true" or "false", as well as to take into account an empty string (which I expected to be interpreted as false).

I was very wrong.

The Boolean() function does not parse a string, but simply tests the truthiness of the parameter passed to it. So, a string of "false" is interpreted as truthy because the string is not null.

I now go to ponder the true meaning of "truth"... :)


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

A Red Herring When Using Moq to Mock Methods With Optional Parameters