Uncategorized

== vs ===

JavaScript language provides two comparison operators for comparing the equality of the two values. It sometimes can cause a big confusion to the execution of the code if it is not clearly understood how these internally works. I’ll try to explain these differences using some examples.

Type Coercion

Type Coercion means that when the operands are different types, one of these operands will be converted to an equivalent value of the other operand’s type. This comparison is mostly done to a number. This implicit conversion process is known as Type Coercion.

For example: ‘2’ == 2 returns true.

‘==’ equality operator

A.k.a. loose equality operator and are considered evil by some. They are evil because syntactically the code would just look just fine but the output of the comparison could be something like unexpected. Here is the reason why this unexpected behavior can happen. == Operator tries to implicitly convert the type of one of the operands to a common type and then doing the comparison between them. Java-script would not complaint about the types mismatch but try to smartly do type coercion and present a result. Few developers find it scary and it can cause various bugs into the system. Consider following examples and see for yourself what this can cause:

1 == 1 //returns true;

1 == ‘1’ is executed as 1 == ToNumber(‘1’), hence 1 == 1 // returns true

‘1’ == 1 is executed as ToNumber(‘1’) == 1, hence 1 == 1 // returns true

undefined == null // returns true

new String(“”) == true//returns true because an object is always true

“” == true //returns false because empty string is considered false

“” == false //returns true because empty string is considered true.

Above mentioned examples apply to all condition constructs in JavaScript for example an ‘if’ statement.

‘===’ equality operator

A.k.a. strict equality operator would also take into account the data type of the operands before doing the comparison. It will simply return false if the types are different. In case of objects, the instances being compared should refer to the same instance to be truthy.

Here are some examples:

1===1   //returns true

1===’1’ //returns false

“” === false //returns false

 

Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s