Type Conversion in JavaScript wrt boolean, undefined, and null

bishnucit

Bishnu Prasad Chowdhury

Posted on January 30, 2021

Type Conversion in JavaScript wrt boolean, undefined, and null

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"

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bishnucit
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