The binary logical operators && and || are used to determine whether an expression is true or false.
&& means the expression on both the side of the operator should be true.
let x = (y==1) && (z==2)
Even if one of the expressions is false the final expression evaluates to false
|| means any of the two expressions should be true
let x = (y==1) || (z ==2)
If any of the two expressions in the above operation is true , the output of x is true , otherwise false.
If you are a java programmer you would expect the result of any binary logical operation to return either true or false like above.
It can return a string or a number too in addition to boolean values!
Any of the below are considered as falsy:
- The boolean value ‘false’
- An empty string ”
- NaN (Not a Number)
Everything else is considered Truthy.
And instead of returning the boolean values ‘true’ or ‘false’ it returns the operand which is either ‘truthy’ or ‘falsy’.
For example consider the below expression:
let x = 'java' && 'angular'
This is because both the strings ‘java’ and ‘angular’ are considered ‘Truthy’.
But then why did it return ‘angular’ and not ‘java’?
- If the first operand is ‘falsy’ return that result , else return the next operand
So in the above expression since ‘java’ is not falsy , it returns angular.
One more example below:
let x = '' && 'angular'
The output of x is the empty string ” in the above case.
Since an empty string is considered as ‘falsy’ , it is returned straight away without even considering the second operand.
What about the logical OR (||) operation?
If it is ‘truthy’ it is returned , else return the second operand
So the below code :
let x = 'java' || 'angular'
returns ‘java’ since it is truthy.
and the below code :
let x = '' || 'angular'
returns ‘angular’ since the first operand ” is not truthy.
Leave a Reply