Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit data type conversion in JavaScript when comparing integer with string using ==

The code:

var num = 20;

if(num == "20")
{
    alert("It works");
}
else
{
    alert("Not working");
}

The question:

  1. 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.

  2. The code above will prompt me an alert box with the message "It works" that shows the if test condition is evaluate to true.

  3. 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?

like image 780
caramel1995 Avatar asked Oct 02 '11 07:10

caramel1995


People also ask

What is the difference between == and which one allows for type coercion?

!! 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.

Does JavaScript support implicit type conversion?

In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.

How do you convert a string to an integer in JavaScript?

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.


1 Answers

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.

like image 51
Bill Avatar answered Oct 05 '22 23:10

Bill