Skip to main content

How to Check if a Variable is a String in JavaScript

In JavaScript, a dynamically-typed language, it's a crucial practice to validate the type of a variable before you attempt to perform operations on it. A common requirement is to check if a variable holds a string before you call a string-specific method like .trim() or .toUpperCase().

This guide will teach you the definitive, standard method for this task using the typeof operator. You will also learn about other, less reliable methods and understand why typeof is the recommended best practice for its simplicity and accuracy.

The typeof operator is a built-in JavaScript operator that returns a string indicating the type of the unevaluated operand. It is the simplest, fastest, and most reliable way to check for a primitive string.

The syntax:

typeof myVariable === 'string'

where:

  • typeof myVariable: This will return the string "string" if myVariable is a string primitive.
  • === 'string': This performs a strict equality check against the expected return value.

Basic Example: A Simple Type Check

This script uses the typeof operator to correctly identify a string.

const myString = "Hello, world!";
const myNumber = 42;

// --- Check the string ---
if (typeof myString === 'string') {
console.log(`'${myString}' is a string.`);
} else {
console.log(`'${myString}' is NOT a string.`);
}
// Output: 'Hello, world!' is a string.

// --- Check the number ---
if (typeof myNumber === 'string') {
console.log(`${myNumber} is a string.`);
} else {
console.log(`${myNumber} is NOT a string.`);
}
// Output: 42 is NOT a string.

This method is also safe to use on variables that have not been declared, as it will not throw an error.

if (typeof undeclaredVar === 'string') {
// This block will not run
}
console.log(typeof undeclaredVar);
// Output: "undefined"

How the typeof Operator Works

The typeof operator is a fundamental part of the JavaScript language. It directly queries the JavaScript engine for the primitive type of a given value. It correctly identifies all primitive types:

Valuetypeof Result
"hello""string"
42"number"
true"boolean"
undefined"undefined"
{}"object"
[]"object"
null"object" (a famous quirk)
function(){}"function"

Because its behavior is so well-defined and predictable for strings, it is the ideal tool for this check.

Alternative Methods and Why to Avoid Them

You may see other, more complex methods online, but they have significant drawbacks.

The Pitfall of the instanceof Operator

The instanceof operator checks the prototype chain of an object. It is not reliable for checking for primitive strings.

Example of code with problems:

const primitiveString = "I am a primitive";
const objectString = new String("I am an object");

console.log(primitiveString instanceof String); // Output: false
console.log(objectString instanceof String); // Output: true
note

This is a problem because 99.9% of all strings in JavaScript are primitives, not String objects created with a constructor. Using instanceof will give you a false negative for almost all normal strings. For this reason, instanceof should not be used to check for a string.

The Pitfall of Object.prototype.toString.call()

This is an advanced technique that can accurately determine a value's internal [[Class]] property.

The syntax:

Object.prototype.toString.call(myVar) === '[object String]'

While this works correctly, it is overly complex and verbose for a simple type check. The typeof operator achieves the same result with much clearer and more concise code. There is no practical advantage to using this method for checking for strings.

Conclusion

For checking if a variable is a string in JavaScript, there is one clear, standard, and recommended method.

The key takeaways are:

  1. The typeof operator is the definitive tool for the job. It is fast, reliable, and its intent is clear.
  2. The correct and most robust syntax is if (typeof myVariable === 'string').
  3. Avoid using instanceof for checking for primitive strings, as it will almost always give you an incorrect result.
  4. While other complex methods exist, typeof is the most direct and readable solution.