Hone logo
Hone
Problems

JavaScript String Type Checker

In JavaScript, it's common to work with various data types. Accurately identifying if a given value is a string is crucial for robust code, preventing unexpected errors and ensuring operations are performed on the correct type of data. This challenge will test your ability to reliably determine if a JavaScript variable holds a string.

Problem Description

Your task is to create a JavaScript function named isString that accepts a single argument. This function should return true if the provided argument is a string, and false otherwise.

Key Requirements:

  • The function must be named isString.
  • It must accept exactly one argument.
  • It should return a boolean value (true or false).

Expected Behavior:

  • If the input is a primitive string (e.g., "hello", '', "123"), the function should return true.
  • If the input is not a primitive string (e.g., a number, boolean, object, array, null, undefined, a String object), the function should return false.

Edge Cases to Consider:

  • String objects created with new String("...") should be considered non-primitive and thus return false.
  • null and undefined should return false.
  • Empty strings ("") should return true.

Examples

Example 1:

Input: "Hello, world!"
Output: true
Explanation: The input is a primitive string.

Example 2:

Input: 123
Output: false
Explanation: The input is a number, not a string.

Example 3:

Input: new String("I am a string object")
Output: false
Explanation: The input is a String object, not a primitive string.

Example 4:

Input: null
Output: false
Explanation: null is not a string.

Example 5:

Input: ""
Output: true
Explanation: An empty string is still a string.

Constraints

  • The function must be implemented in standard JavaScript.
  • No external libraries are allowed.
  • The solution should be efficient.

Notes

Consider the different ways strings can be represented in JavaScript, especially the distinction between primitive strings and String objects. Think about the built-in JavaScript methods or operators that can help you differentiate between these types.

Loading editor...
javascript