0
const addCode = function (code) {
    console.log("Add Code executed");
    var JS = document.createElement('script');
    JS.textContent = code;
    document.body.appendChild(JS);
}

(() => {
    // Run once on script start up
    console.log("Startup site.js ran");
    $.get("A2040/GetLoggingMessageData", (data, status) => {
        console.log(`Data: ${data} \nStatus ${status}`);
        addCode(data);
    })
})(); // Immidiately Invoked

Declaring the addCode function the ES5 way (maybe) hoists it and runs before console.log("Startup site.js ran");.

  1. Why would it do that? Declaring the same function with the arrow syntax functions as expected - first it logs Startup site.js ran then it logs Add Code executed.
const addCode = (code) => {
    console.log("Add Code executed");
    var JS = document.createElement('script');
    JS.textContent = code;
    document.body.appendChild(JS);
}
  1. Why is it now doing it correctly with an arrow function? What's happening?
Maksim Dimitrov
  • 113
  • 2
  • 11
  • The second syntax is using an [Arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) inside an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE). The arrow function retains the scope of the calling context, and the IIFE is, as its name implies, invoked immediately. The issue you're seeing with the order of execution is entirely because of your use of the IIFE - this is why the latter example works as you expect, with the caveat of the execution scope. – Rory McCrossan Mar 29 '19 at 14:40
  • @freedomn-m Yes yes, I meant declaring the addCode function – Maksim Dimitrov Mar 29 '19 at 14:49
  • @RoryMcCrossan I still don't understand why would it run before the "Startup site.js ran" log with the old syntax, but it will ran after it with the arrow syntax – Maksim Dimitrov Mar 29 '19 at 14:54
  • 1
    You forgot a semicolon after `addCode` declaration, so it's called immediately because of parentheses after it. – Alexey Lebedev Mar 29 '19 at 14:54
  • @AlexeyLebedev That's it. Can't believe this. Thanks! A good reason to discountinue ANY work wihtout making Visual Studio lint my code and have proper JS support ... – Maksim Dimitrov Mar 29 '19 at 14:59
  • @AlexeyLebedev Interesting though, why would ommiting the semicolon works with an arrow function – Maksim Dimitrov Mar 29 '19 at 15:02
  • 1
    @MaksimDimitrov good question, I don't know. Automatic semicolon insertion rules are quite complicated. But you can see that [AST for arrow](https://astexplorer.net/#/gist/4c49c19256a2b31cfd6eddbd297970b0/6a276b783aadde883eb64fc714e7c8159ff39461) is very different from [AST for function](https://astexplorer.net/#/gist/ef378a7320215926b15dc1fe412239d1/007efe39d5ce19fbde7aeff8cb8f85380fc8e14b). – Alexey Lebedev Mar 29 '19 at 17:07

0 Answers0