What do you know about Conversion and Coercion in Javascript?
There are times you want to convert your data from number to string or from string to number or from number to Boolean, or you want to store a zip code of an area or a telephone number, how do you do it? Let’s assume I want to store ‘6' in a string format. It will go thus.
let num = String(6)
console.log(num, typeof num);
You can also do reverse, as in you have a number in string format and you want to perform operation on it. First, you have to convert it into a num by simply saying:
let num = Number("123")
As for coercion, it happens when there are two different data and you want to perform operation, these operations have to come to some consensus, either both has to be of same type e.g. both string or both numbers. For example:
let x
console.log(x, typeof x); //undefined undefined
x = 8
console.log(x, typeof x); //8 number
Output for above = undefined undefined; 8 number. It is so because the ‘x’ in 2 has a data accompanied.
Another example:
let x
console.log(x, typeof x); //undefined undefined
x = 8
console.log(x, typeof x); //8 number
x = " "
console.log(x, typeof x); //8 string
x = x - 2
console.log(x, typeof x); //6 number
As for Boolean, you manipulate them with the use of operators e.g ‘!’. It means ‘not’. Hence, it changes the type from ‘true’ to ‘false’ and vice versa. Example
x = !x
console.log(x, typeof x); //false
Another instance,
console.log(Boolean(7)); //true
Note that all numbers are true, except zero which is false. The actual implementation of Boolean happens in a way that 0 is false and other numbers are true. They are called Truthy and Falsy values.
When you pass objects into Boolean, it gives you true.
For functions , it gives you true .
Passing a string like ‘Aisha’ into Boolean, output is true.
However, for undefined values, it gives you false.
Whenever you have a number and a string, it will convert into string when you apply the addition operator, but when you perform the subtraction operation, it converts into number.
ParseInt — a special function that accepts a string and converts it to an integer or number. Example
let x = ParseInt("123 Aisha")
console.log(x); //123
However, if you have a character at the start, e.g.
let x = ParseInt("W123 Aisha")
console.log(x); //NAN
Output= NAN(Not A Number).
See you next time!