0

Context: this is not a request for help, I found the solution, I just want to understand why.

Working code:

  var username_result = (await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A" + selrow,
  })).data;

This returns the expected object, and I can log it to console to view its contents.

If I remove the outer set of parentheses, i.e. making this not an IIFE, username_result is undefined.

I read through this question and it seems to suggest that googleSheets.spreadsheets.values.get({}).data would otherwise not return any value if not wrapped as an IIFE. I looked at the documentation for this function and it explicitly states that it returns a range of values.

I hate implementing code that I don't fully understand. Why does this need to be an IIFE to work?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 1
    Side note: `var` is deprecated. Use `let` or `const` in new code in modern environments. – T.J. Crowder Apr 29 '22 at 16:41
  • Oh, I had no idea. Why is that, if you don't mind? I came from mostly coding for Acrobat and Photoshop. Acrobat doesn't even allow let statements. – Joseph Massaro Apr 29 '22 at 16:48
  • 1
    There are several reasons. :-) 1. Repeated declarations in the same scope aren't an error. 2. It only has global or function scope, not block scope. 3. It initializes the binding (loosely, "variable") with `undefined` upon entry to the scope, meaning you can access the variable before (seemingly) you've declared it. 4. At global scope, it creates properties on the global object, which is already plenty crowded. :-) `let` and `const` fix those issues. (And I should say: It's not *officially* deprecated, it's just...not best practice going forward.) Happy coding! – T.J. Crowder Apr 29 '22 at 17:02

1 Answers1

2

That's not an IIFE. It's just the grouping operator (parentheses).

You need it because await has lower precedence than property access. So with it, you're awaiting what you get from get(/*...*) and then reading the data property from the result of the await. Without it, you're accessing a data property on the promise get(/*...*/) returns (it doesn't have one) and using await on the resulting value (undefined).

So you need the grouping operator, or you could use destructuring:

var {data: username_result} = await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A" + selrow,
});

...or just two statements:

const result = await googleSheets.spreadsheets.values.get({
    auth,
    spreadsheetId,
    range: "users!A" + selrow,
});
var username_result = result.data;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875