half of a glazier
half of a glazier

Reputation: 2076

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

enter image description here

^ Mouse is hovering over hours so current value is visible

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?

Upvotes: 1

Views: 593

Answers (5)

Lokesh Suman
Lokesh Suman

Reputation: 503

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

if hours = 1 then

hours is true: 1

or if hours = 0 then

hours is false: 0

or if hours = 20 then

hours is true: 20

Upvotes: 0

Styler
Styler

Reputation: 32

You have to check the data type:

typeof hours;

0 as number return false in if statement, that's why with ! it return true.

var number = 0;
if (number) console.log(true); else console.log(false);
output -> false
if (!number) console.log(true); else console.log(false);
output -> true

That's clear JS.

Upvotes: -1

mbojko
mbojko

Reputation: 14679

I put a breakpoint here, and set hours = 0 in the debugger.

And that's probably the source of confusion. If your "here" is after the code tested the value of x, then your changing the value of x doesn't affect which branch gets executed.

Upvotes: 0

Beginner
Beginner

Reputation: 9095

Check this one, open the devtools and run the code snippet, change the scope value to 0 or in the console put hours = 0. Both will work tested it

Chrom version : Version 79.0.3945.88 (Official Build) (64-bit)

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

Upvotes: 2

karkael
karkael

Reputation: 473

Have you carefully parsed the hours received ?

!0 === false
!"0" === true
!parseInt("0") === false

Have you computed string as if it was integer ?

"0" +  0  === "00"
 0  + "0" === 0
+"0" + 0  === 0

Upvotes: 0

Related Questions