JavaScript Check a Variable is String

Published on October 2, 2020 23 sec read

In this article, we’re going to check a variable is string in JavaScript. Let’s see:

Method 1

We can any variable type using typeof operator. The typeof operator returns a string indicating the type of the unevaluated operand.

Have a look at example:

let varName = 'mynotepaper';

if (typeof varName === 'string') {
    console.log('It is a string');
} else {
    console.log('It is not a string');

Method 2

We can create a reusable function to check variable. Create a function:

function checkString(val){
  if(typeof val === 'string'){
      return true;
  return false;

Now call the function and get result:

let varName = 'mynotepaper';
let varName2 = 123456;

checkString(varName); // true
checkString(varName2); // false
That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.