javascript casting
cast primitive variables quite easily
string to number
cast by multiplying by 1
var num1 = 123;
var num2 = '123';
console.log(num1 + num2);//"123123"
console.log(num1 + num2 * 1);//246
console.log(num1 == num2);//true
console.log(num1 === num2);//false
console.log(num1 === num2 * 1);//true
cast by adding (thanks to mallowigi)
var num1 = '11';
console.log(num1 + 2);//"112"
console.log(+num1 + 2);//13
cast in array index
var arr = ["aaa", "bbb", "ccc"];
console.log(arr["1"]);//"bbb"
Object to boolean
use double exclamation mark
console.log(!!undefined);//false
console.log(!!'abc');//true
console.log(!!0);//false
console.log(!!1);//true
console.log(!!'0');//true
Written by Ron Apelbaum
Related protips
1 Response
You can also use the unary +
var a = '123';
+a + 234; // 357
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#