How to Check if a Variable is a String in JavaScript

JavaScript Check if String

This quick tip will show you how to check if a variable is a string in the JavaScript Programming Language.

What is a String?

string is a type of variable. A variable type determines what values a variable can contain and what can be done with the variable.

Strings are a series of characters – letters or numbers or symbols. They can be joined, split, and iterated over.

Strings are used to store words, sentences, and other non-numeric data like encoded images or serialized data which is going to be transmitted.

Checking if a Variable is a String with JavaScript’s typeof

The typeof command in JavaScript returns the type of the object it is called on. It returns a string containing the name of the type.

In this case, we want to check that the type of the variable named testMe is “string” – so a simple comparison can be used:

if (typeof testMe === 'string') {
    // String
}
else {
    // Not a string
}

The === operator is used to ensure that the typeof the given variable is an exact match for “string” – both in value and type.

Checking if a Variable is Not a String

The reverse can also be done by reversing the equality check:

if (typeof testMe !== 'string') {
    // Not a string
}
else {
    // String
}

Why?

There are any number of reasons why you would want to check if a variable is or is not a string based on your use case. For example, you may wish to check that values are not strings before trying to perform arithmetic or boolean logic on them.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published.