JavaScript Casting Tricks

Hold on Cowboy

This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.

Here I want to go through some casting tricks that can be used for better data manipulation.


Build in Boolean() 

The easiest way is to use the builtin Boolean() method.

Boolean('true'); // true
Boolean(1); // true

Boolean('false'); // true !!!!GOTCHA!!!!!
Boolean(0); // false

// Careful
Boolean([]); // true

Double Negative 

This will cast anything as either true or false, there are of course a few quirks that may not be obvious.



// GOTCHA!!! ... TRUE


This will parse the text 'true' to the boolean true



// If using a variable, you'll want a fallback
JSON.parse(undefined || 'true');
JSON.parse('' || 'true');


Check for a decimal using modulo 

5.5 % 1 != 0; // true
5 % 1 != 0; // false



Built in tools toString() and String() 

var hello = String('hello')

Casting an Array as a String 

Strings are of course mostly just an array of characters so arrays and strings have a lot in common. You can cast an array to a string simply by joining them with nothing.

var hello = ['h', 'e', 'l', 'l', 'o'];
hello.join('');  // Yields "hello"

Convert from an Array to a String 

Strings can be converted to an array easily using split. Here’s how.

var hello = "hello";
hello.split('');  // ['h', 'e', 'l', 'l', 'o'];


In JavaScript the arguments object in a function is array like, but to convert it to an actually array you can just use a simple trick.;

Or more simply if Array generics are available (like in node.js).


Have one to add? Comment below. 

Did this help you out? It took me a few days to piece together all this information together, I hope this saves you some time (who knows, maybe the future me will be thankful I wrote this down). Let me know your thoughts.