How to check if a variable is a string in JavaScript

In this article, we will see how to easily check if a given variable is a string or not using JavaScript.

In JavaScript, we can use the typeof operator to check the datatype of a variable.

The typeof operator returns a string indicating the type of the value.

For example to check if a variable is a string or not :

var variable = 'Hello'
console.log(typeof variable) // string

When we console log it, the operator returns string.

We can also write it with if..else statement using equality condition to do some tasks based on the data type of the variable. For Example:

var variable = 'Hello World';

if (typeof variable === 'string') { // returns true
  console.log('data-type is a string');
} else {
  console.log('data-type is not a string');

Now, important to note that typeof operator will return object for array, null, and object.


console.log(typeof null); // object
console.log(typeof []); // object
console.log(typeof {}); //object

However, if you create a string using the new String() constructor, the typeof operator will return it as an object.

var str = new String('Hello World')

console.log(typeof str) // object

And, if we just use the String() constructor, the operator will return it as a string.

var str = String('Hello World')

console.log(typeof str) // string

The reason is that the new keyword creates an instance of the String type whereas, the function String() returns a primitive String.

The above two constructor examples are just to understand how it works with the typeof operator and it is not really used that much in programming.

💾 Recommended Articles