How the binary logical operators ‘&&’ and ‘||’ differ in Javascript from Java

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.

Example:

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.

But that is not how Javascript works!

It can return a string or a number too in addition to boolean values!

This is because Javascript has this concept of Truthy and Falsy.

Any of the below are considered as falsy:

  • The boolean value ‘false’
  • An empty string ”
  • NaN (Not a Number)
  • null
  • undefined

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’.

So a binary logical operation can return anything in javascript!

For example consider the below expression:

let x = 'java' && 'angular'

This will be invalid in Java programming language but it returns the value ‘angular’ in javascript.

This is because both the strings ‘java’ and ‘angular’ are considered ‘Truthy’.

But then why did it return ‘angular’ and not ‘java’?

That is because javascript follows the below rule for the logical AND (&&) operator:

  • 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?

In this case as well, javascript checks only the first operand.

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.

That’s it!


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading