How to Check If Variable is String in JavaScript

To check if a variable is a string in JavaScript, you can use the “typeof” operator. The typeof operator returns a string representing the type of the given variable. If the variable is a string, the typeof operator returns “string”.

Syntax

typeof varName;

Parameter

Variable name 

Return value

The data type of the variable.

Example

const stringVariable = "Harry Potter Web Series";
const nonStringVariable = 42;

if (typeof stringVariable === "string") {
  console.log("stringVariable is a string");
} else {
  console.log("stringVariable is not a string");
}

if (typeof nonStringVariable === "string") {
  console.log("nonStringVariable is a string");
} else {
  console.log("nonStringVariable is not a string");
}

Output

stringVariable is a string

nonStringVariable is not a string

In this example, the code checks if stringVariable and nonStringVariable are strings by comparing the result of typeof to the string “string”. The check returns true for stringVariable and false for nonStringVariable.

This approach checks the variable type, not whether its value is an instance of the String object. If you need to check for both string primitives and String objects, you can use the following function:

function isString(variable) {
  return typeof variable === 'string' || variable instanceof String;
}

This function checks if the given variable is a string primitive or an instance of the String object and returns true if either condition is met.

However, it’s generally recommended to use string primitives in JavaScript, as they have better performance and are more commonly used.

Leave a Comment