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 run.

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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.