Q:

How to Check If a Variable is a String in JavaScript

0

How to Check If a Variable is a String in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the typeof Operator

You can simply use the typeof operator to determine or check if a variable is a string in JavaScript.

In the following example just play with the myVar value to see how it works:

// Sample variable
var myVar = 'Hello';

// Test if variable is a string
if(typeof myVar === 'string') {
    alert('It is a string.');
} else {
    alert('It is not a string.');

You can also define a custom function to check whether a variable is a string or not.

The custom isString() JavaScript function in the following example will return true if the variable is a string otherwise return false. Let's try it out and see how it works:

// Defining a function
function isString(myVar) {
    return (typeof myVar === 'string');
}
    
// Sample variables
var x = 10;
var y = true;
var z = "Hello";
    
// Testing the variables
alert(isString(x)); // Outputs: false
alert(isString(y)); // Outputs: false
alert(isString(z)); // Outputs: true

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Set Default Parameter Value for a JavaScrip... >>
<< How to Convert Decimal Values to Hexadecimal in Ja...