How to Check If a Variable is a String in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the typeof Operator

You can simply use the typeof operator to determine or check if a variable is a string in JavaScript.

In the following example just play with the myVar value to see how it works:

// Sample variable
var myVar = 'Hello';

// Test if variable is a string
if(typeof myVar === 'string') {
    alert('It is a string.');
} else {
    alert('It is not a string.');

You can also define a custom function to check whether a variable is a string or not.

The custom isString() JavaScript function in the following example will return true if the variable is a string otherwise return false. Let's try it out and see how it works:

// Defining a function
function isString(myVar) {
    return (typeof myVar === 'string');
// Sample variables
var x = 10;
var y = true;
var z = "Hello";
// Testing the variables
alert(isString(x)); // Outputs: false
alert(isString(y)); // Outputs: false
alert(isString(z)); // Outputs: true

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties