Understanding differences between == and === in JavaScript

Understanding differences between == and === in JavaScript

Introduction

In JavaScript, two commonly used equality operators are == (equality operator) and === (strict equality operator). Although they may appear similar, a notable destination exists between the two understanding the difference is very important to write a bug-free code.

The equality operator ( ==)

The == in JavaScript attempts to convert operands to the same type before making the conversion. This conversation can lead to some unexpected results if not understood carefully.

If the operands are of different types JavaScript tries to convert them into common type before making the comparison

console.log( 10 == '10') // return true

The strict equality operator ( === )

The === in JavaScript checks both value and type equality between the operands. In general, it is recommended to use the === operator for equality comparison because it avoids any type of unexpected type coercion.

console.log( 10 === '10' ) // return false
console.log( 10 === 10 ) // return true