Logical Operators: PHP vs JavaScript

I’ve come across this condition from this PR (scroll down to the bottom) and wondered how it really works.

if ( 'object' === typeof window && window.app && window.app.isDebug ) {
	// something here
	// redacted to focus on the if condition
}

My first fast* thought was this checks if all types of of window, windows.app, and window.app.isDebug are object. If so, that’s something too new to me!

Second slower* thought was my first thought is wrong! Yeah, indeed, it’s wrong. It would be checking type of window. If it’s true, it will continue checking if window.app is a falsy value. Then again if window.app.isDebug is a falsy value. As soon as, an expression is false, the whole condition will be false. In other words, I expected that the value of expression between two parentheses is either true or false.

I want to confirm in the console, then try with the code below. I expect that I will get true:

let dat = {
    name: 'Dat Hoang',
}

console.log( 'object' === typeof dat && dat.name )

But the reality is very different: Dat Hoang.

Why does that happen? I really need to look at JavaScript logical operators, and a surprise shows up in my eyes: the AND operator can return something else rather than just only true/false:

… the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

It’s so different from what I know (mostly PHP) and I found the most voted note in PHP Logical Operators doc is extremely helpful:

Note that PHP’s boolean operators *always* return a boolean value… as opposed to other languages that return the value of the last evaluated expression.

https://www.php.net/manual/en/language.operators.logical.php#usernotes

Big Lessons Learnt

  • PHP and JavaScript handles these logical operators differently!
  • Stop using PHP thoughts in JavaScript.
  • Double-check everything! Without double-checking, I may spend hours of debugging for something like this in a production code later.

* Fast and slow are two main terms in Thinking, Fast and Slow book.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s