Stephanos
Stephanos

Reputation: 571

Checking if value exists and is (or is not) zero in JavaScript always returns zero instead of boolean

I'm trying to check if a number exists and if it does, whether the value is zero or something else. Checking for zero though always returns zero instead of a boolean value.

const example = 0

console.log( example === 0 )            // true 
console.log( example && example !== 0 ) // 0
console.log( example && example === 0 ) // 0

I know this may have something to do with zero being falsy in JS but I don't understand why it evaluates to 0 in the two last cases - if anything, shouldn't it evaluate to false?

Upvotes: 1

Views: 896

Answers (2)

user3252327
user3252327

Reputation: 627

If you want to get a boolean that tells if the number is defined and different from 0 you can use !!example. Here is a breakdown in typescript to better understand types we are manipulating:

// let's assume the value you want to check is a number or undefined
boolean function isDefinedAndDifferentFromZero(num: number | undefined) {
  const temp1: boolean = !num; // true if num is falsy (undefined or 0), false if num is truthy (number defined and different from 0)
  const isTruthy: boolean = !temp1; // negates temp1 and actually gives a boolean telling whether num is truthy or falsy
  return isTruthy; // note that isTruthy is just !!num
}

Upvotes: -1

vighnesh153
vighnesh153

Reputation: 5388

In computer science, there is a concept of short-circuiting. If two or more conditions are bundled together with an && (logical "and") and if the first condition evaluates to false, then it just returns the result of the first condition, instead of also evaluating the second one.

In this case, 0 is falsy and hence, the second condition is not evaluated and the result of the first one is returned.

Upvotes: 6

Related Questions