Hone logo
Hone
Problems

JavaScript: Is This Really a Boolean?

In JavaScript, differentiating between various data types is crucial for writing robust and predictable code. Sometimes, you need to specifically identify if a given value is a boolean (true or false). This challenge will test your ability to accurately determine if a variable holds a boolean value, avoiding common pitfalls.

Problem Description

Your task is to create a JavaScript function that accepts a single argument and returns true if the argument is strictly a boolean primitive (true or false), and false otherwise.

Key Requirements:

  • The function must accurately distinguish between the boolean primitives true and false and any other JavaScript data type.
  • The function should not consider strings like "true" or "false", numbers like 1 or 0, or other objects as booleans.

Expected Behavior:

  • If the input is true, the function should return true.
  • If the input is false, the function should return true.
  • For any other input (e.g., numbers, strings, arrays, objects, null, undefined, functions), the function should return false.

Edge Cases:

  • Consider inputs that might be easily confused with booleans, such as 1 and 0, or the strings "true" and "false".

Examples

Example 1:

Input: true
Output: true
Explanation: The input is the boolean primitive `true`.

Example 2:

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

Example 3:

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

Example 4:

Input: 1
Output: false
Explanation: The input is a number, not a boolean primitive.

Example 5:

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

Example 6:

Input: []
Output: false
Explanation: The input is an array, not a boolean primitive.

Constraints

  • The function will be tested with various JavaScript data types.
  • The function should be efficient and have a time complexity of O(1).

Notes

Consider using JavaScript's built-in mechanisms for type checking. Be mindful of the difference between primitive types and their wrapper objects (though for booleans, this distinction is less common to encounter in typical scenarios). The typeof operator might be a good starting point, but it's not always sufficient on its own for all type-checking scenarios.

Loading editor...
javascript