How do you reliably check if a variable is a string in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you reliably check if a variable is a string in JavaScript?

message-square
0

Checking whether a value is a string in JavaScript seems obvious with typeof, until you run into boxed String objects (new String("abc")), cross-frame values, or values that just look like strings. Knowing the difference between string primitives and String instances prevents subtle bugs in validation and serialization.


1. Primitive Strings vs. String Objects

Most of the time in JavaScript, you want to know if a value is a primitive string (typeof value === "string"):

function isStringPrimitive(value) {
  return typeof value === "string";
}

console.log(isStringPrimitive("hello"));      // true
console.log(isStringPrimitive(""));           // true (empty string is still a string)
console.log(isStringPrimitive(123));          // false
console.log(isStringPrimitive(new String("hello"))); // false (object wrapper)

If you also want to treat boxed new String("...") instances as strings—including across iframes or realms—use Object.prototype.toString.call():

function isAnyString(value) {
  return (
    typeof value === "string" ||
    Object.prototype.toString.call(value) === "[object String]"
  );
}

console.log(isAnyString("hello"));                 // true
console.log(isAnyString(new String("hello")));     // true

2. Checking for Non-Empty Strings Safely

A common follow-up check is making sure a value is both a string and not blank/whitespace-only:

function isNonEmptyString(value, { trim = true } = {}) {
  if (typeof value !== "string") return false;
  return trim ? value.trim().length > 0 : value.length > 0;
}

console.log(isNonEmptyString("  api_key  ")); // true
console.log(isNonEmptyString("   "));        // false
console.log(isNonEmptyString("   ", { trim: false })); // true

3. Common Traps to Avoid

  • Assuming typeof catches new String(): typeof new String("abc") returns "object", not "string". Avoid new String() in everyday code, but handle it if you consume third-party or legacy objects.
  • Confusing String(val) conversion with type checking: Calling String(null) produces "null" and String(42) produces "42". That coerces values into strings—it does not tell you if the original value already was one.
  • Truthy checks (if (val)) instead of string checks: Truthy checks reject "" (valid empty string) and accept non-strings like 1 or {}.

TL;DR: Use typeof value === "string" for standard primitive string checks, add Object.prototype.toString.call(value) === "[object String]" only if you need to match boxed String objects, and avoid String(value) when you want a boolean type check rather than coercion.

Are you validating user form inputs, checking API payloads, or guarding against boxed String objects?