"Semantics" or "Translation Problem"


#1

Maybe it’s late (technically speaking, really early in the morning) and I need to get some sleep at last – but I’m having trouble seeing why this

if (n % 2)

is logically equivalent to this

if (n % 2 !== 0)

'cause the first reads to me as “if n is divisible by 2 without remainder” while the second reads as “if n is not divisible by 2 without remainder” and yet they both work the same!!!

Thanks, as always, for any insight…


#2

Oh, never mind – I see it now: the if really means “if (something is true)” so if (n % 2) and if (n % 2 !== 0) both wind up being truethat’s what’s important to JavaScript!

Though higher-level languages are meant to help us humans program easier by replicating human syntax and thought processes, there’s no guarantee that any given situation will “parse well!”

“Problem” solved.


#3

Read up on truthy and falsy and how they relate to booleans. An if statement, like a while statement yield a boolean from their conditional expression.

if (condition) {

}

while (condition) {

}

condition is always either true or false. That means that any expression can be cast to a boolean just by making it a conditional.

7 > 6

A comparison is a boolean expression.

1

A non-zero number (or non-empty string) will always cast to true. They are said to be truthy. Zero (and the empty string) will always cast to false, since they are falsy.

a = Math.floor(Math.random() * 2)
console.log(a ? 'truthy' : 'falsy');

If you are not familiar with ternary expressions, or are generally unclear on what an expresson is, then you have some more reading to do.

condition ? is_truthy : is_falsy;

Expressions always yield a value. Even functions can be expressions, as in,

foo = function () {

};

console.log(foo());    // undefined

undefined above does not mean the function returns that value, it means that the return value is undefined. That in itself is a sort of value, though in truth a value does not exist.