mercredi 8 janvier 2020

If statement treating true as false

I have stumbled across an extremely strange occurrence in Javascript that I can't make head or tail of.

Here's a very simple if statement:

let hours = 20;

I put a breakpoint here, and set hours = 0 in the debugger. I test !hours in the debugger to confirm the result is true, and click continue to run through the if statement.

if (!hours) {
  console.log("Hours is false: " + hours);
} else {
  console.log("Hours is true: " + hours);
}

Expected result to be logged:

Hours is false: 0

Actual result logged:

Hours is true: 0

This only happens when hours was originally set to an integer, and then set to 0 in the debugger. Does Javascript have some obscure rule about truthy values retaining their status even after being changed?

Or is this a discrepancy between the debugger and the code (which, if true, would basically defeat the point of the console)?

Why on earth is this happening?

Aucun commentaire:

Enregistrer un commentaire