Comparing JavaScript for Automation (JXA) and AppleScript

As @ComplexPoint has pointed out many times if you do not put all of your JXA code in a function, then it gets mixed in with the global JavaScript environment.
And, Script Editor sometimes (always?) remembers the values of variables from the prior execution.

@ComplexPoint can explain all of this much better than I can.

So, here's a simple anonymous function that @ComplexPoint provided elsewhere:

(() => {
    'use strict';

    // Do everything in this purely local space, 
    // inside the definition of a nameless function, 
    // which is immediately executed because of the ( ) at the end.
    //Script Editor runs your JS in a global environment which persists between script runs.

})(); 

For the JXA template I use, see MACRO: [JXA] Template -- KM

3 Likes