Home > front end >  Checking if value exists and is (or is not) zero in JavaScript always returns zero instead of boolea
Checking if value exists and is (or is not) zero in JavaScript always returns zero instead of boolea

Time:09-23

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?

CodePudding user response:

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.

CodePudding user response:

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
}
  • Related