JavaScript: Truthiness and Falsiness Converter
In JavaScript, not all values are explicitly true or false. Many values have an inherent "truthy" or "falsy" nature when evaluated in a boolean context. Understanding this concept is crucial for writing concise and correct conditional logic. This challenge will test your ability to convert various JavaScript data types into their boolean equivalents.
Problem Description
Your task is to create a JavaScript function named convertToBoolean that accepts a single argument of any JavaScript data type. The function should return the boolean representation of that argument.
Key Requirements:
- The function must handle all primitive data types (strings, numbers, booleans, null, undefined, symbols, bigints) and common object types (arrays, objects, functions).
- The function should accurately reflect JavaScript's built-in truthy and falsy rules.
- The function should not rely on explicit comparisons like
value === trueorvalue === falseunless absolutely necessary for specific edge cases or to demonstrate understanding. Instead, leverage JavaScript's implicit type coercion.
Expected Behavior:
- Falsy values should be converted to
false. - Truthy values should be converted to
true.
Important Edge Cases:
- Consider empty strings vs. non-empty strings.
- Consider the number
0vs. other numbers. - Consider
nullandundefined. - Consider empty arrays and objects vs. non-empty ones.
Examples
Example 1:
Input: 0
Output: false
Explanation: The number 0 is a falsy value in JavaScript.
Example 2:
Input: "Hello"
Output: true
Explanation: Any non-empty string is a truthy value in JavaScript.
Example 3:
Input: []
Output: true
Explanation: An empty array is considered a truthy value in JavaScript, even though it's empty.
Example 4:
Input: null
Output: false
Explanation: `null` is a falsy value in JavaScript.
Example 5:
Input: {}
Output: true
Explanation: An empty object literal is considered a truthy value in JavaScript.
Constraints
- The function must be written in JavaScript.
- The function should take exactly one argument.
- There are no specific performance constraints for this challenge, but strive for idiomatic and efficient JavaScript.
Notes
JavaScript has a defined set of falsy values:
false0(the number zero)-0(the number negative zero)0n(BigInt zero)""(the empty string)nullundefinedNaN(Not-a-Number)
All other values, including empty arrays ([]), empty objects ({}), and functions, are considered truthy. Consider how you can leverage JavaScript's built-in mechanisms to determine truthiness without explicitly listing all possible truthy values.