Hone logo
Hone
Problems

Determining Boolean Values in JavaScript

JavaScript's type system can be a bit quirky when it comes to booleans. This challenge asks you to write a function that accurately identifies whether a given value is a true boolean value (either true or false), distinguishing it from values that JavaScript loosely coerces to booleans. This is crucial for reliable conditional logic and data validation.

Problem Description

You need to create a JavaScript function called isBoolean that takes a single argument, value, and returns true if the value is a boolean primitive (either true or false). It should return false otherwise. The function must correctly handle various input types, including primitives, objects, and potentially unexpected values. It's important to differentiate between a true boolean and a value that JavaScript coerces to a boolean (e.g., 0, 1, null, undefined, empty strings, etc.).

Key Requirements:

  • The function must accept any JavaScript value as input.
  • The function must return true only if the input is the boolean primitive true or false.
  • The function must return false for all other input types, including numbers that evaluate to true/false, strings, objects, null, undefined, and NaN.
  • The function should not rely on loose type coercion (e.g., !!value).

Expected Behavior:

The function should behave as follows:

  • isBoolean(true) should return true
  • isBoolean(false) should return true
  • isBoolean(1) should return false
  • isBoolean(0) should return false
  • isBoolean("true") should return false
  • isBoolean("") should return false
  • isBoolean(null) should return false
  • isBoolean(undefined) should return false
  • isBoolean({ value: true }) should return false
  • isBoolean([true]) should return false
  • isBoolean(NaN) should return false

Examples

Example 1:

Input: true
Output: true
Explanation: The input is the boolean value true.

Example 2:

Input: false
Output: true
Explanation: The input is the boolean value false.

Example 3:

Input: 1
Output: false
Explanation: The input is a number, not a boolean.  While 1 is loosely coerced to true, we need to check for the *boolean primitive*.

Example 4:

Input: "true"
Output: false
Explanation: The input is a string, not a boolean.

Example 5:

Input: null
Output: false
Explanation: The input is null, not a boolean.

Constraints

  • The function must be written in JavaScript.
  • The function must accept any JavaScript value as input.
  • The function must not use loose type coercion (e.g., !!value).
  • The function should be efficient and avoid unnecessary operations.

Notes

Consider using the typeof operator to determine the type of the input value. Remember that typeof true and typeof false both return "boolean". However, be mindful of how typeof interacts with other data types. The key is to specifically check for the values true and false.

Loading editor...
javascript