Isak Berglind • February 10, 2019
php javascriptComming from php, I noticed something in javascript that I found pretty wierd - how the the logical or operator || behaves.
In php, the expressions on boths sides of the or operator is being casted to a boolean. So
false || true // true
0 || '' // false
'' || 0 // false
null || "Hey!" // true
In javascript, however, if the first expression is truthy, it returns it, otherwise it returns the second expression
false || true // true
0 || "" // ""
"" || 0 // 0
null || "Hey!" // "Hey!"
Hmm. Doesn't that behaviour seem familiar? It does! It just how the php ternary shorthand operator works
"" ?: 0 // 0
0 ?: "" // ""
This i quite handy! Especially because javascript dosen't support the shorthand ternary.
Sometimes you want the php behaviour thought. How can you solve that? You simply need to convert the expression to a boolean yourself. That can be done in several ways. Here are a few:
Boolean("" || 0) // false
!! ("" || 0) // false
!! "" || !! 0 // false
This gave me a real head scratch a while back, as i got some unexpected resuilts. I hope this short article might help another confused developer venturing from php to javascript :)
Ps. The same non casting behaviour goes for the logical and (&&) operator. Read more about it here