Three Invaluable shortcuts for type conversion in Javascript

As Javascript developers we dream in type. Here are three quick and easy ways to convert from one type to the other in your Javascript code.

Well, just kidding about the whole dream part. Most of us don’t quite care about types as much as we should.

Anyhow, here are three quick ways to convert types -

Convert to number

Use +.

console.log(+1); // 1
console.log(+"1"); // 1
console.log(+"a"); // NaN
console.log(+true); // 1
console.log(+null); // 0
console.log(+undefined); // NaN
console.log(+0); // 0

Convert to string

Use ''+ or ''.concat().

console.log("" + 1); // 1
console.log("".concat(1)); // 1

console.log("" + "1"); // 1
console.log("" + "a"); // a
console.log("" + true); // true
console.log("" + null); // null
console.log("" + undefined); // undefined

We have seen this shortcut earlier as well.

And, by the way, the undefined, null etc. depicted above are strings.

console.log(typeof ("" + undefined)); // string

Convert to boolean

Use !!.

console.log(!!1); // true
console.log(!!"1"); // true
console.log(!!"a"); // true
console.log(!!true); // true
console.log(!!null); // false
console.log(!!undefined); // false

Also see

comments powered by Disqus