What is the best way to check the type of a variable in JavaScript?
In the following code snippet:
function saveName(firstName) {
function capitalizeName() {
return firstName.toUpperCase();
}
var capitalized = capitalizeName();
console.log(capitalized instanceof String); // This shows false
return capitalized; }
console.log(saveName("Robert")); // Returns "ROBERT"
I want to check the type of the capitalized variable using capitalized instanceof String, but it returns false. I don’t want to use capitalized instanceof Function or Object, as that would take too much time.
What is the best way to JavaScript check type?
Hi,
The simplest way to check the type of a variable is by using the typeof operator. It returns a string that represents the type of the unevaluated operand. In your case, you can check the type of capitalized like this:
var typeOfCapitalized = typeof capitalized;
console.log(typeOfCapitalized); // Output: "string"
This method is quick and easy, making it a great choice for javascript check type.
Another method to check if a variable is specifically a string is to compare it directly with the string constructor. This will also work for string literals and string variables:
var isString = capitalized.constructor === String;
console.log(isString); // Output: true
Using this approach provides a clear way to javascript check type while ensuring you’re checking against the String constructor.
If you need to perform a more comprehensive type check, you can use the Object.prototype.toString.call() method.
This method returns the exact type of the variable:
var typeOfCapitalized = Object.prototype.toString.call(capitalized);
console.log(typeOfCapitalized); // Output: "[object String]"
By utilizing this method, you can achieve a precise javascript check type that can differentiate between various types, including distinguishing strings from other types like objects.