Hone logo
Hone
Problems

Determine the JavaScript Type of Any Value

Understanding the data type of a value is fundamental to writing robust JavaScript code. This challenge will test your ability to accurately identify the type of various JavaScript values, which is crucial for conditional logic, data validation, and proper handling of different data structures.

Problem Description

Your task is to create a JavaScript function, getJsType, that accepts a single argument of any JavaScript type. The function should return a string representing the precise type of the input value.

Key Requirements:

  • The function must handle all primitive data types (string, number, boolean, null, undefined, symbol, bigint).
  • It must also correctly identify object types, including arrays, functions, regular expressions, dates, and plain objects.
  • The returned string should be descriptive and consistent across different JavaScript environments.

Expected Behavior:

For a given input, getJsType should return a specific string that accurately describes its type. For instance, a number should return "number", an array should return "array", and a function should return "function".

Edge Cases to Consider:

  • null is a special case in JavaScript, often behaving like an object but having a distinct type.
  • Distinguishing between different kinds of objects (e.g., arrays vs. plain objects).
  • The behavior of typeof for certain values.

Examples

Example 1:

Input: 123
Output: "number"
Explanation: The input is a standard integer literal.

Example 2:

Input: "hello"
Output: "string"
Explanation: The input is a string literal.

Example 3:

Input: [1, 2, 3]
Output: "array"
Explanation: The input is an array, which is a specific type of object.

Example 4:

Input: null
Output: "null"
Explanation: null is a primitive value representing the intentional absence of any object value.

Example 5:

Input: function() {}
Output: "function"
Explanation: The input is a function declaration.

Example 6:

Input: {}
Output: "object"
Explanation: The input is a plain object literal.

Constraints

  • The function should be named getJsType.
  • The function must accept exactly one argument.
  • The returned type string should be lowercase.
  • Performance is not a primary concern for this challenge; correctness and clarity are prioritized.

Notes

The built-in typeof operator in JavaScript can be a useful starting point, but it has some limitations (e.g., typeof null returns "object", and it doesn't differentiate between various object subtypes like arrays). You may need to combine typeof with other checks to achieve the desired precision. Consider using Object.prototype.toString.call() for more detailed type inspection.

Loading editor...
javascript