I wanted to check whether a variable in an Apps Script was a String, but found that instanceof wasn't returning true when the variable was in fact a string. The following test:
function test_instanceof() {
var a = "a";
Logger.log('"a" is ' + ((a instanceof String) ? '' : 'not ') + 'a String');
var b = String("b");
Logger.log('String("b") is ' + ((b instanceof String) ? '' : 'not ') + 'a String');
}
Logs these two messages:
"a" is not a String
String("b") is not a String
The docs aren't clear on the subset of ECMAScript that is supported, though apparently instanceof is a valid operator and String is a valid type, judging from the fact that the code executed without an exception.
What is the appropriate way to check the type of a variable?
It's standard EcmaScript 3.
Your code is doing what JavaScript expects: see here for the equivalent JavaScript running in your browser.
Instanceof checks for a matching constructor in the prototype chain. That's good for objects created via 'new' but not very helpful for strings. What you actually want for String is typeof, as shown in this example in your browser or the equivalent Apps Script code:
function test_instanceof() {
var a = "a";
Logger.log('"a" is ' + ((typeof a == 'string') ? '' : 'not ') + 'a String');
var b = String("b");
Logger.log('String("b") is ' + ((typeof b == 'string') ? '' : 'not ') + 'a String');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With