Check if a Variable is a String using JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

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'). The typeof operator returns a string that indicates the typeof of a value. If used with a string, the typeof operator returns "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 execute.

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

index.js
if (typeof variable === 'string') { console.log('โœ… type is string'); } else { // ๐Ÿ‘‡๏ธ this runs console.log('โ›”๏ธ type is NOT string'); }

We had not declared the variable we used the typeof operator on, so it returned a string of "undefined", instead of throwing an error.

index.js
console.log(typeof doesNotExist); // ๐Ÿ‘‰๏ธ "undefined"

Note that no automatic type conversion is performed and even if your variable contains a number that is wrapped in a string, it still would pass as a 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"

Notice the new keyword. There is no good reason to use the new String() constructor, and I have never seen someone use it.

Note that the String constructor is not the same as the string function, 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 new keyword), produces an instance of the String type and should never be used.

Whereas, the function returns a primitive string.

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

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee