Predict the output of the following JavaScript code

function checkTruthy(value) {
  if (value) {
    return "truthy";
  } else {
    return "falsy";
  }
}

console.log(checkTruthy(0));
console.log(checkTruthy(""));
console.log(checkTruthy(null));
console.log(checkTruthy(undefined));
console.log(checkTruthy(NaN));

 

 

 

 

The trick here lies in JavaScript's falsy values. In JavaScript, certain values are considered "falsy" when evaluated in conditional statements like if. These falsy values include:

  • false
  • 0 (the number zero)
  • "" (an empty string)
  • null
  • undefined
  • NaN (Not a Number)

The checkTruthy function checks if the provided value is truthy (any value that evaluates to true in a conditional statement) or falsy. However, there's a subtle detail:

  • The function returns "truthy" only if value is explicitly true.

Therefore, the output will be:

falsy  // 0 is a falsy value
falsy  // "" (empty string) is falsy
falsy  // null is falsy
falsy  // undefined is falsy
falsy  // NaN is falsy (although technically not strictly equal to false)

Correct Answer:

b) falsy, falsy, falsy, falsy, falsy