JavaScript Check a Variable is String

Published on October 2, 2020 23 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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

Author

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

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *