Open In App
Related Articles

Check if a variable is a string using JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will check if a variable is a string using JavaScript. We can check the variable by using many methods. Checking the type of a variable can be done by using the typeof operator. It directly applies either to a variable name or to a variable.

Below are the following methods through which we can check the type of variable is a string:

  • Using typeOf
  • Using Instanceof Operator
  • Underscore.js _.isString()

Approach 1: Using typeOf

Syntax:

typeof varName;
  • varName: It is the name of the variable.

Example: This Example checks if the variable boolValue and numValue is a string. 

Javascript




let boolValue = true;
let numValue = 17;
let bool, num;
 
if (typeof boolValue == "string") {
    bool = "is a string";
} else {
    bool = "is not a string";
}
if (typeof numValue == "string") {
    num = "is a string";
} else {
    num = "is not a string";
}
console.log(bool);
console.log(num);


Output

is not a string
is not a string

Approach 2: Using Instanceof Operator

The instanceof operator in JavaScript is used to check the type of an object at run time.

Syntax:

let gfg = objectName instanceof objectType

Example:

Javascript




let variable = new String();
 
if (variable instanceof String) {
  console.log("variable is a string.");
} else {
  console.log("variable is not a string.");
}


Output

variable is a string.

Approach 3: Underscore.js _.isString()

The _.isString() function is used to check whether the given object element is string or not.

Syntax:

_.isString( object )

Example:

Javascript




let info = {
    Company: 'GeeksforGeeks',
    Address: 'Noida',
    Contact: '+91 9876543210'
};
console.log(_.isString(info));
 
let str = 'GeeksforGeeks';
console.log(_.isString(str));


Output:

false
true

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 10 Aug, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials