DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

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

Top comments (2)

Collapse
 
shrihankp profile image
Shrihan

Number, Boolean and String are not really keywords, these are Classes or Constructor Functions built-in to JavaScript.

Collapse
 
bishnucit profile image
Bishnu Prasad Chowdhury

You are correct i didnot meant javascript keyword I will edit.