Type Conversion in JavaScript wrt boolean, undefined, and null
Bishnu Prasad Chowdhury
Posted on January 30, 2021
We can convert to a string type using the String class
let a = 5;
typeof(a);
> "number"
typeof(String(a));
> "string"
let b = true;
String(b);
> "true"
let c = undefined;
String(c);
> "undefined"
let d = null;
String(d);
> "null"
Similarly, to convert to a number we can use the Number class
let a = "5" ;
typeof(a);
> "string"
typeof(Number(a));
> "number"
let b = true;
Number(b);
> 1
let c = undefined;
Number(c);
> NaN
let d = null;
Number(d);
> 0
//when an operator is there it auto converts
// to number unless its a + operator
let e = "6" / "2";
e
>3
let e = "6" + "2";
e
>62
Converting to Boolean uses Boolean class like String and Number.
let a = "5" ;
typeof(a);
> "string"
typeof(Boolean(a));
> "boolean"
let b = true;
Boolean(b);
> true
let c = undefined;
Boolean(c);
> false
let d = null;
Boolean(d);
> false
💖 💪 🙅 🚩
Bishnu Prasad Chowdhury
Posted on January 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev A Tale of WeakMap and WeakSet in JavaScript: The Guardians of Forgotten Secrets
November 29, 2024