Type conversions in javascript refer to the ability to convert from one data type to another. For example, we can convert numbers to strings as follows;
console.log(typeof(30 + 'years'));//string
If javascript fails to perform a meaningful type conversion i.e tries to make an impossible conversion, for example, a string to a number, the result is NaN.
console.log(Number(30 + 'years')); //NaN
You should note that when two numbers presented as stings are added together, the result is a string. Example;
console.log(typeof('2' + '3')); //string
This is because javascript doesnโt actually perform the typical addition functionality that is represented by the + operator but instead performs string concatenation. This means it treats the two numbers just like any other string, and when two strings are combined, the result is a string type.
console.log('2' + '3'); //23
On the other hand, if we were to perform a different operation example multiplication, division, or subtraction, then javascript would automatically convert the strings into a number and perform the actual arithmetic operation. Examples;
console.log('2' * '3'); //6
console.log(typeof('2' * '3')); //number
console.log('2' - '3'); //-1
console.log(typeof('2' - '3')); //number
console.log('6' / '3'); //2
console.log(typeof('6' / '3')); //number
console.log('6' % '3'); //0
console.log(typeof('6' % '3')); //number
You can share this article on your social media to bookmark it for future reference or give access to your friends also working or interested in javascript language. You can follow me on Twitter , where I share countless resources and articles related to javascript and we can become lifetime friends and javascript lovers.
Finally,** THANK YOU** so much for taking your time to read this article. If you are feeling more generous I'll not stop you from buying me a cup of coffee.
Until the next article, KEEP CODING & SHARING.
Top comments (0)