JavaScript Check a Variable is String
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. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.