Table of contents
No headings in the article.
Let’s talk about a very interesting and might be a funny sometimes topic in Javascript. Javascript can convert type according to the operator and values on which this operator is applied. This type of conversion on runtime can be very odd and may return unexpected results while doing arithmetic operations.
What it does, first see the examples given below, now We will look at them one by one.
In the first line as we multiply 5 with the null value so what it will return is 0 because the javascript multiply operator will check the type of both of its operands, and coerce that operand to a number if it is not. So null will be converted to 0, which again results in 0.
For the second-line operator minus will behave the same as multiplication as coerce the operands to number if they are not already.
In the third statement, we have a plus operator (also used as strings concatenation) which will look If the first operand is of string type then it will convert the second operator to string and concatenate both. If the first operator is of number type it will coerce the second one to the number and the result will be the sum of two numbers.
In the 4th statement, the multiply operator will return NaN Because it will try to convert that string to a number like this Number(“five”), which returns NaN, and the arithmetic operation with NaN will always return NaN.
In the fifth statement, we have the == operator which will also coerce both operands to the same type which why returns true even different-looking operands. The same rule will be applied to the sixth and seventh statements.
Hope you understand the Automatic Type Conversion which can be called accidental conversion If you write it unintentionally🙂.