[logo] a small computer

Javascript Gotchas I've Encountered in The Wild

javascript gotchas i've encountered in the wild

Bradley Kingsley
Published a year ago.
1 minute read
logo of undefined

Casting a String to A Boolean in Javascript

The first programming language I ever learnt was Java. In the Java world, the need to cast different types of fields to other fields is one that comes up quite commonly.

If I wanted to cast a string to a boolean, I'd do something like

	String trueOrFalseString = "false";
	boolean castBoolean = (boolean) trueOrFalseString;

Naturally, my assumption was that I could do the same in Javascript, like so:

	let isOpenBoolean = localStorage.getItem(shouldModalBeOpen);
	if (Boolean(isOpenBoolean)){
		//close modal
	}

isOpenBoolean is null by default, causing the modal to always be shown the first time around. When a button is clicked, I set it to false. Now, keep in mind, localStorage always stores values as strings, including booleans.

So, woe unto me when the modal ended up being shown every time. A little StackOverflow later and it turns out:

	Boolean("any_string")

is always true! It makes sense once you've wrapped your head around Javascript falsiness and truthiness, but by God... 😅

Also, honourable mention:

  string=(string==String(string?true:false))?(string?true:false):(!string?true:false); 

can be used for the same purpose if you like complexity for whatever reason. Thanks to Mark K for that one.

Copyright © 2020 The Kenyan Dev