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 +
.
1
2
3
4
5
6
7
|
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()
.
1
2
3
4
5
6
7
8
|
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.
1
|
console.log(typeof ("" + undefined)); // string
|
Convert to boolean
Use !!
.
1
2
3
4
5
6
|
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