Difference between "==" and "===" in JS

·

1 min read

In JavaScript "==" and "===" are both used for comparing values. Heres the difference between the two:

\==(Equality Operator):

The '==' checks for equality between two values after converting them to a common type. If the values of comparision are of different types then java script will attempt to convert them into a common type before making the attempt of comparision.

For example, 1=='1' will return true because java script converts the string '1' to number 1 before comparing them. This type conversions can sometimes leads to unexpected results, so it is generally recommended to avoid using '==' operator for comparisions.

\===(Strict Equality Operator):

The '===' operator also known as strict equality operator, checks for equality between two values without performing any type of conversion. It returns 'true' if values are of the same type and have the same value.

For example, 1=='1' will return false because the values are of different types 'number' and 'string'. Using '===' is considered best practice for comparisions in java script because it avoids the potential pitfalls of type conversion that can occur with '=='.

In summary, '==' perform type coercion before comparision while '===' doesn't. It is generally safer to use '===' for comparisions to avoid unexpected behaviour.