Why is the following true: "Dog" === ("Cat" && "Dog")

javascript

Solution

Think of `&&` in JavaScript like this (based on ToBool from the es5 spec)

function ToBool(x) {
    if (x !== undefined)
        if (x !== null)
            if (x !== false)
                if (x !== 0)
                    if (x === x) // not is NaN
                        if (x !== '')
                            return true;
    return false;
}

// pseudo-JavaScript
function &&(lhs, rhs) { // lhs && rhs
    if (ToBool(lhs)) return rhs;
    return lhs;
}

Now you can see that `ToBool("Cat")` is `true` so `&&` will give `rhs` which is `"Dog"`, then `===` is doing `"Dog" === "Dog"`, which means the line gives `true`.

For completeness, the `||` operator can be thought of as

// pseudo-JavaScript
function ||(lhs, rhs) { // lhs || rhs
    if (ToBool(lhs)) return lhs;
    return rhs;
}

Problem

Why does the `&&` operator return the last value (if the statement is true)? ``` ("Dog" == ("Cat" || "Dog")) // false ("Dog" == (false || "Dog")) // true ("Dog" == ("Cat" && "Dog")) // true ("Cat" && true) // true (false && "Dog") // false ("Cat" && "Dog") // Dog ("Cat" && "Dog" && true) // true (false && "Dog" && true) // false ("Cat" && "Dog" || false); // Dog ``` Fiddle

Original source