The code:
var num = 20;
if(num == "20")
{
alert("It works");
}
else
{
alert("Not working");
}
The question:
In C programming we have a rule name data type promotion, where when there's a mix of data type (example: addition of integer and floating point), the integer will first converted to floating point before the addition is being carry out.
The code above will prompt me an alert box with the message "It works"
that shows the if
test condition is evaluate to true.
For loosely typed JavaScript, I'm just curious: is there any rule like C that determines which conversion will be carry out in which situation? Besides that, the JavaScript code above converts num
variable value from an integer value to string value before making comparison or vice versa?
!! operator converts both 'true' and 'false' strings to boolean true , since they are non-empty strings. Then, == just checks equality of two boolean true's without any coercion. == operator triggers a numeric conversion for an array.
In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
Avoid implicit type conversion in JavaScript. Always take steps to test and/or convert individual values before comparing them to ensure you are comparing apples to apples. Always test explicitly for undefined to determine if a value or property has a value, use null to indicate that object variables or properties do not refer to any object, and convert & compare all other values to ensure operations are performed against values of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With