How to use Object.prototype.toString.call Method In Javascript
The Object.prototype.toString.call method is a reliable way to determine the type of a variable. It returns a string indicating the type of the object.
Syntax:
Object.prototype.toString.call(variable) === '[object String]'
Example: This example shows the implementation of the above-explained approach.
function checkIfString(variable) {
if (Object.prototype.toString.call(variable) === '[object String]') {
console.log("variable is a string.");
} else {
console.log("variable is not a string.");
}
}
// Test cases
checkIfString("Hello, World!");
checkIfString(42);
checkIfString(true);
checkIfString({});
checkIfString(new String("Test"));
Output
variable is a string. variable is not a string. variable is not a string. variable is not a string. variable is a string.
Check if a variable is a string using JavaScript
In this article, we will check if a variable is a string using JavaScript. We can check the variable by using many methods.
Below are the following methods through which we can check the type of variable is a string:
Table of Content
- Using typeOf Operator
- Using Instanceof Operator
- Underscore.js _.isString()
- Using Lodash _.isString() Method
- Using Object.prototype.toString.call Method
Contact Us