Check if a Variable is a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a Variable is a String in JavaScript #

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string'). If the typeof operator returns "string", then the variable is a string. In all other cases the variable isn't a string.

index.js
const variable = 'hello'; if (typeof variable === 'string') { // 👇️ this runs console.log('✅ type is string'); } else { console.log('⛔️ type is NOT string'); }

We used the typeof operator to check if a variable is a string.

The operator returns a string that indicates the type of the value.

Here are some examples:

index.js
console.log(typeof ""); // 👉️ "string" console.log(typeof "hello"); // 👉️ "string" console.log(typeof "42"); // 👉️ "string" console.log(typeof function () {}); // 👉️ "function" console.log(typeof null); // 👉️ "object" console.log(typeof []); // 👉️ "object" console.log(typeof {}); // 👉️ "object" console.log(typeof 0); // 👉️ "number"
If the variable stores a string, the equality condition will return true and the if block will run.

The typeof operator is very flexible because it doesn't throw an error, even if you use it on a variable that has not been declared.

index.js
if (typeof variable === 'string') { console.log('✅ type is string'); } else { // 👇️ this runs console.log('⛔️ type is NOT string'); }

We used the typeof operator with a variable that hasn't been declared, so it returned a sting of "undefined".

index.js
console.log(typeof doesNotExist); // 👉️ "undefined"

Note that no automatic type conversion is performed. If your variable contains a number that is wrapped in a string, the typeof operator still returns "string".

index.js
console.log(typeof '42'); // 👉️ string

The only scenario where the typeof operator wouldn't detect a string is if the string is created using the new String() constructor.

index.js
const str = new String('hello world'); console.log(typeof str); // 👉️ "object"

Note that the String() constructor is not the same as the String object. The difference being the new keyword.

index.js
console.log(typeof new String('hello')); // 👉️ "object" console.log(typeof String('hello')); // 👉️ "string"

The String() constructor (with the new keyword), produces an instance of the String type and should never be used.

Whereas, the String object is used to convert a value to a string.

The typeof operator is all you need to check if a variable stores a string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.