Last Updated: February 25, 2016
·
991
· apelbaur

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

1 Response
Add your response

You can also use the unary +
var a = '123'; +a + 234; // 357

over 1 year ago ·