DEV Community

moadhN
moadhN

Posted on

Why is it you can execute a function on the right side of an AND && operator in JavaScript

I always assumed that operators like && and || are for comparing true and false statements on both sides.

But I'm seeing a pattern in React where, on the right side is a function and the left is a truthy statement that will then allow the right to be executed.

Example:

truthy statement && function
Enter fullscreen mode Exit fullscreen mode

I understand that JavaScript will check this from left to right, so left being true will then allow it to check the right. But my assumption is the right should expect a true or false statement, but in this case it's just a function.

I'm so used to seeing the && operator in this context:

if (true && true) {
  // Execute this
}
Enter fullscreen mode Exit fullscreen mode

That this:

true && execute this
Enter fullscreen mode Exit fullscreen mode

Works at all.

I guess my assumption is that JavaScript will just evaluate anything next to an operator whether it returns a true or false.

Top comments (0)