Why JavaScript Why? - Type Coercion
JavaScript's odd behaviour around type coercion and comparisons that makes that happen at their own.
So, I recalled different problem statements in Java script which were quite odd For ex-
15+"12" //1512
but
"12"-5 //7
typeof +"12" //number
Why such behaviour comes in the picture gonna discuss about it in detailed so next time you can never be tricked with JS different type coercion's behaviour. It feels kind of scrulls in captain marvel who can change their shapes . They are less predictable though .
What is it??
Automatic conversion of data types (like boolean to the number and strings to numbers or numbers to boolean ) is referred to type coercion.
Why its confusing ??
Reason behind this is we don't dig enough to know that how it behaves differently and how the foremost important conversation got to understand this in short time.
What is revolves around?
If not explicitly done than it revolves mostly around the operands and comparisons . It happens every time we perform different actions it works and behaves differently with different actions gonna fasten your belts gonna discuss to them in deep.
Thumb Rules to keep in mind always
1)Number conversion of some values that are unpredictable
for ex-
undefined =>NaN
null=>0
true=>1
false=>0
anyString=>0(if its empty else NaN)
2)Unary Operand (+) converts a string to a number
for ex- const a="2"
console.log(typeof +a) //number
3)While comparing in the greater or smaller types between different types of the data types Js tries to converts the value to the numbers so in specific cases like
ex- null>0 //false
null<=0 //true
null==0 //false
The problem here is not created by the data types but the comparison types so when you compare things with <= or >= or <= = or = = > and if the data compared is not of same data type they get's converted into a number for the comparison . While == never converts the datatype to number .
Conclusion
This was a whole try the example codes in your code editor once and you will reveal some of the dark sides of JS. Thanks for reading