0

On my first acquaintance with Google Apps Script I wrote a script which picks three files on my Drive and writes the full paths to them in a text file. It seems to be working fine. getFullPathById(id) is another function I wrote which is irrelevant here.

function main() {
  outputfilename = "out.txt"
  content = ""

  var i = 0
  allfiles = DriveApp.getFiles()
  while (i < 3 && allfiles.hasNext())
  {
    file = allfiles.next()
    content += getFullPathById(file.getId())
    i = i + 1
    console.log(i)
  }

  DriveApp.createFile(outputfilename, content)
}

Though when instead of var i = 0 I simply wrote i = 0 it processed not three files but two, and logged 2 2 4 to console instead of 1 2 3. Further when I changed i < 3 to i < 5, it processed not 5 but twenty-something files. Where I, a newbie in Google Apps Script, can read about differences between writing var i = 0 and i = 0?

Cooper
  • 59,616
  • 6
  • 23
  • 54
dnes
  • 101
  • 3
  • 2
    Do you have `i` defined at the global level outside of the `main()` function or in other scripts in your GAS project? If so, your `main()`function is likely referencing some other declaration of `i`. Variables declared using `var` are hoisted so that they are scoped to the function they are in. Use of `var` is now discouraged in favor of `let` and `const` which are block-scoped. – TheAddonDepot Jul 01 '23 at 22:01
  • Did @TheAddonDepot comment answer your question? You can also read more information about this in the following [Post](https://stackoverflow.com/questions/1470488). – Giselle Valladares Jul 04 '23 at 20:12
  • @GiselleValladares pretty much yes – dnes Jul 06 '23 at 04:25

1 Answers1

1

I'm writing this answer as a community wiki for visibility, since the solution was provided by @TheAddonDepot in the comments section.

var i = 1 declares variable x in current scope (aka execution context). If the declaration appears in a function - a local variable is declared; if it's in global scope - a global variable is declared.

i = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then does it creates the i property on a global object (which is a top level object in a scope chain).

Also, as mentioned by @TheAddonDepot. The use of var is now discouraged in favor of let and const, you can read more information about the difference between var, let and const in the following blogs:

Giselle Valladares
  • 2,075
  • 1
  • 4
  • 13