Type Conversion - Javascript

Converting a number into string.

let year = 2001;

console.log(typeof year);

Its console output will be

Now if we try to get length of year, we will get undefined as output.

let year = 2001;

console.log(typeof year);
console.log(year.length);    // number data type don't have a length method, length is only defined for string

Now if we want to convert value of variable year into a string , we need to wrap it into a String function

let year = 2001;

console.log(typeof year);
console.log(year.length);

console.log(typeof String(year));
console.log(String(year).length);

Now you can see third and fourth row in output, you can see in third row output is string and in fourth row the length of the string is given as 4.

Now let's see what happen if we try to convert a mathematical expression into a string ?

console.log(String(4+9-7))
console.log(typeof String(4+9-7))

Output:

6
string

As you can see in the output above first the mathematical expression is evaluated which will be a number and then that number is convered to a string.

 

Converting a boolean to string

console.log(true);
console.log(typeof true);

console.log(String(true));
console.log(typeof String(true));

Output:

 

Converting a date to string

console.log(new Date());
console.log(typeof new Date());

console.log(String(new Date()));
console.log(typeof String(new Date()));

Output:

 

Converting array to string

console.log([3,7,9,1]);

Output:

As you can see in output , first row is an object while second row is an string, if we expand first row output we can see the full object.

 

So far we have used String function wherever we needed a conversion to string data type. We can use an alternative toString method to achieve same kind of results.

// toString Method

console.log((5).toString());
console.log((true).toString());

 

 

 

Convert String to number

// Convert String to number
let age = Number('51');
console.log(typeof age);

 

If we convert a boolean to number

// Convert String to number
console.log(Number(true));
console.log(Number(false));

Output:

Questions : What will happen if we try to convert

1) a null to a number

2) a String which is not a number

Answer:

// Convert String to number
console.log(Number(null));
console.log(Number('jack'));

Output:

parseInt and parseFloat

console.log(parseInt('55.23'));
console.log(parseInt('55.97'));
console.log(parseFloat('55.23'));

Output:

Type coersion in javascript

If we add a number which is of data type string with another number which is of data type number

let val1 = '5';
let val2 = 9;
console.log(val1 + val2);

Output : 59

Here what is happened, since 5 was a string , javascript converted 9 into a string too and then concatenated it to 5 hence the output become '59'. 

 

 

 

 

None