Top 4 ways to check if a variable is a string in JavaScript

Marika Lam
2 min readSep 23, 2022

1. Using typeof operator

The recommended solution is to use the typeof operator to determine the type of operand. This is demonstrated below:

const val = ‘Hello World’;if (typeof val === ‘string’) {console.log(‘Variable is a string’);}else {console.log(‘Variable is not a string’);}/*Output: Variable is a string*/

Download Run Code

The typeof operator will return an object for strings created with new String(). This can be handled using the instanceof operator.

const val = new String(‘Hello World’);if (typeof val === ‘string’ || val instanceof String) {console.log(‘Variable is a string’);}else {console.log(‘Variable is not a string’);}/*Output: Variable is a string*/

Download Run Code

2. Using Object.prototype.toString.call() function

Another approach is to find the class of Objects using the toString method from…

--

--