== (equal) vs === (strict equal) in javascript which is faster?
javascript is not strictly typed language which means you can simply define a variable without declaring its type that plays an important role in comparison
js have two options for variable comparison
==
: this checks for values of variable
for eg.
let a = "5";
let b = 5;
console.log(a==b) //prints true
2. ===
: checks for value as well as the datatype of a variable since in the above example a
is of type string
and b
is of type number
it prints false
so what exactly happens when you try to use ==
and which is the faster? and which one to use?
when you use ==
it does coercion of datatype and converts them into one possible datatype then it compares for the value
in the above example, it tries to convert b into a string
there are different coercion rules which you can learn more from here: https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion
since ==
has to do coercion underneath before comparison whereas ===
returns false as soon as it encounters conflicting datatype
conclusion: Always use 3 equals unless you have a good reason to use 2. it’s always good to use predefined datatypes even though js is very forgiving by nature