What does my getter execute, if var/const is omitted in Google apps script?

Viewed 144

Assume the following piece of code, which runs fine

var Loader = { // Can be 'const' as well 
  get db() {
    throw('exception');
  }
}
function test(){
   console.log("I'm fine")
}

test()

And almost the same, with var omitted, which is also fine(in javascript)

Loader = { // Can be 'const' as well 
  get db() {
    throw('exception');
  }
}
function test(){
   console.log("I'm fine")
}

test()

However, if second one is run inside Google Apps Script(assuming you run function test) it fails on exception, trying to execute throw('exception') from getter of 'db' property. Why is that?

Error: https://imgur.com/6ocjHGY

Sample script

1 Answers

From a pure JavaScript point of view, the difference between global variables created using the var keyword or using no keyword at all is the configurability bit of the property that's created on the global object:

foo = 1;
Object.getOwnPropertyDescriptor(this, "foo")
// {value: 1, writable: true, enumerable: true, configurable: true}

var bar = 2;
Object.getOwnPropertyDescriptor(this, "bar")
// {value: 2, writable: true, enumerable: true, configurable: false}

So in most cases, you wouldn't notice that difference, but it is detectable if you insist on finding it.

Now, why this affects the behavior of GAS, I have no idea. Looks like some part of that framework iterates over all configurable properties of the global object and their sub-properties. I'm not familiar with GAS so I don't know why it might want/have to do that. If it matters to you, maybe file a bug to ask?

Does it happen with all variable names? --Bergi

Yes, it happens for Loader.db just as it does for MyLoader.mydb, so it's not just an unlucky collision with one particular built-in thing.

Related