Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof String not behaving as expected in Google Apps Script

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?

like image 996
James Synge Avatar asked Jul 20 '12 02:07

James Synge


1 Answers

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');
}
like image 153
Corey G Avatar answered Nov 01 '22 18:11

Corey G