This page looks best with JavaScript enabled

Type Casting in Javascript

 ·   ·  ☕ 2 min read

Don’t know how to type? Get a typewriter.

I always wanted to say that. But, if indeed you don’t know types - you can always head over to Javascript types to know more**.

So, you know there are types. And, you also know that there can be many a problem in the lousy world of loose typing. (I just felt like the next S waxing such eloquence).

The only choice to make here is to know more about how to convert from one type to other, and remain type-safe. And, that will quickly become second nature to your programming style.

When and where should I use type casting?

It is a good practice to use type conversion wherever you are not in control of the types. For e.g. you are processing user data, working with unreliable data that has changed shape over years, receiving data from an external program, etc.

How should I type cast?

Converting types is a simple affair.

From _ to String

Either use String(x) or x.toString.

1
2
3
42.toString();    //"42"
String(true);     //"true"
String(undefined);//"undefined"

 

From _ to Number

This is radically different from string.

1
2
3
4
5
6
7
Number("0"); // 0
"24".toNumber(); // 24

Number("abc"); //NaN
// NaN = not a number

Number(true); // 1

 

Did I say radically different? Yes - that referred to using ‘Number’ instead of ‘String’, and not using toNumber - that is radical.

There are additional helper functions like -

1
2
parseInt("42life"); //42
parseFloat("3.14pi"); //3.14

 
.. that can level-up your casting.

From _ to Boolean

Following the tradition established by now, you will understand that the following is used for Boolean.

1
2
Boolean("a"); // true
Boolean(null); // false

While on the topic of type conversions and checking for the ‘truth’, you may have noticed that 1, non-null string, and a boolean true are all the same.

We use such things inter-operably in the if/else and other loop checks.

1
2
3
4
5
if ("apple") want("orange");

if (false) justDoItAgain();

if (1) stopThisAlready();


** Aside: You may need help more than you think if you did what you were told here. You should head over to MDN to know more about types, not a not-so-entertaining, silly post.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things