All logical expressions evaluate from left to right. The logical operators && and || behave differently when dealing with values of different types.
- When the value to the left of the and operator is evaluated to false, the condition returns false
- When the value to the left of the and operator is evaluated to true, it checks if the value to the right is true or false and accordingly provides a result.
console.log(NaN && 0) //NaN console.log(0 && NaN) //0 console.log(NaN && null) //NaN console.log(null && NaN) //null console.log(1 && NaN) //NaN
or operator works the other way around.
- When the value to the left of the or operator evaluates to true, the operation returns true.
- When the value to the left of the or operator is evaluated to false, it checks if the value to the right is true or false and accordingly provides a result.
console.log("" || "user") //user console.log(null || "user") //user console.log("i"||"u") //i
The above code shows an interesting way or works. The first value that evaluates to true is returned.
The cases seen till now are all due to short-circuit evaluation. You can read more about it here.
console.log(2 < 3) //true console.log(10 < 2) //false
This is how a typical relational operator(<,>,>=,<=, etc) works.
But what if we were to compare other data types like below.
console.log("ant" < "Bat") //false console.log("Ant" < "Bat") //true
Strings are compared from left to right. The ASCII representation of strings can be found here. Lowercase letters are always greater than uppercase letters. So the code above is valid.
- Short-circuit evaluation handles logical operation with different data types
- and operator behaves in such a way that it returns the value which evaluates to false
- or operator behaves in such a way that it returns the value which evaluates to true
- Strings are compared from left to right depending on their ASCII value
That's it for this article. Hope you liked it and please leave your comments below. :)