So why do you think the if statement works if the string isn't empty?
Because a non-empty string is truthy, right?
Yeah, do you know what that means?
I think so
Have you actually tried that?
It might be a good idea to take a step back and establish what it means for something to be truthy first. Many people get a feeling for how this works but don’t actually dive into the details. In simple terms, truthiness is just what you get when you throw the variable in question into the Boolean() function.
so any time you’re calling an if statement, what that if statement is actually doing is this:
The Ecma-262 spec defines a function that it refers to as
ToBoolean, and all implicit boolean conversions including the explicit
Boolean() behave according to it with the following lookup table.
|Number||If argument is +0𝔽, -0𝔽, or NaN, return false; otherwise return true.|
|String||If argument is the empty String (its length is 0), return false; otherwise return true.|
|BigInt||If argument is 0ℤ, return false; otherwise return true.|
This might come as a surprise to some. What is truthy and what is falsy is clearly defined for each data type and has nothing to do with equality. This is the reason why you might expect arrays inside if statements to behave the way they do.
An array is an object which is always true regardless of its contents. If you’re a python developer, this is likely confusing since python’s lists implement bool differently and empty lists are considered falsy just like empty strings.
So if truthiness isn’t based on
==, what’s going on with loose equality?
to make sure an array isn’t empty. The same coercion happens when using the loose comparison operator
==, so why is plopping things inside
if statements acceptable but using
ToBoolean is a unary function, meaning it has a single input and so it’s a lot easier to wrap one’s head around than
== which is a binary operator with 2 inputs. But another reason is because loose comparison is actually a recursive operator…
That’s right, loose comparison is implemented recursively. Meaning that comparison between two non-matching data types could recurse as much as 4 times, converting the inputs in each iteration into a different one and re-running the equality check.
There’s an extremely useful website on this topic that visually shows exactly how this process works between different kinds of inputs.
But basically in summary, equality is defined separately from truthiness. The only similarity they share is that truthiness is a form of coercion and loose equality can make use of a similar type of coercion although equality itself does not rely on the concept of truthiness.