Logical operators:
Logical operators in javascript, unlike operators in other programming languages, do
not return true or false. They always return one of the operands.
OR ( | | ) operator - If the first value is truthy, then the first value is returned.
Otherwise, always the second value gets returned.
AND ( && ) operator - If both the values are truthy, always the second value is
returned. If the first value is falsy then the first value is returned or if the second value
is falsy then the second value is returned.
Example:
var x = 220;
var y = “Hello”;
var z = undefined;
x | | y // Returns 220 since the first value is truthy
x | | z // Returns 220 since the first value is truthy
x && y // Returns “Hello” since both the values are truthy
y && z // Returns undefined since the second value is falsy
if( x && y ){
console.log(“Code runs” ); // This block runs because x && y returns “Hello” (Truthy)
}
if( x || z ){
console.log(“Code runs”); // This block runs because x || y returns 220(Truthy)
}
Equality Coercion
Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
The ‘ == ‘ operator compares values and not types.
While the above statement is a simple way to explain == operator, it’s not completely
true
The reality is that while using the ‘==’ operator, coercion takes place.
The ‘==’ operator, converts both the operands to the same type and then compares
them.
Example:
var a = 12;
var b = “12”;
a == b // Returns true because both ‘a’ and ‘b’ are converted to the same type and then
Coercion does not take place when using the ‘===’ operator. Both operands are not
converted to the same type in the case of ‘===’ operator.
Example
var a = 226;
var b = “226”;
a === b // Returns false because coercion does not take place and the operands are of