0

So let's pretend that I have a index.js file with the following scenarios. The file is imported in the index.html file, and it will trigger what is inside of that file. Can I expect the following snippets to behave differently or behave the same? I see the same results, but might as well ask :)

scenario 1

(() => {
  navigator.serviceWorker.register("sw.js").then(() => {
    console.log('sw registered');
  });
})();

scaneario 2

registerServiceWorker();

function registerServiceWorker() {
   navigator.serviceWorker.register("sw.js").then(() => {
        console.log('sw registered');
   });
}

scenario 3

navigator.serviceWorker.register("sw.js").then(() => {
    console.log('sw registered');
});
5
  • 1
    In #2 the function stays in the memory and can be reused, the other cases are not reusable. Commented Jan 31, 2020 at 7:12
  • so for my what you see is literally all i have in the index.js, and i won't to anything else in the file. So i guess it doesn't matter which scenario i do @Teemu Commented Jan 31, 2020 at 7:15
  • I'd use #3, there is nothing IIFEs adds. Commented Jan 31, 2020 at 7:41
  • 1
    Yes, the only difference is, that #2 uses more memory, scripts are not removed from the document until it is unloaded. If this is all the code in the file, I can't see any reason to use structures #1 or #2. Commented Jan 31, 2020 at 7:55
  • @Teemu feel free to put this as a answer Commented Jan 31, 2020 at 17:51

1 Answer 1

1

Sure - they'll behave identically. You might choose one or the other for various reasons, perhaps depending on the context of the code and how you expect the code to evolve. For example, if there might be a need to re-use the function, then you would choose the named function approach. I can't see much point in the ugly verbosity of (1) though.

Sign up to request clarification or add additional context in comments.

2 Comments

this file won't have more code and i don't need to reuse the function. I thought about using the first one and change the code to use async/await. Thoughts? I think that's the only time i see the first one making sense to use
Perhaps over-thinking it. 3 is concise and clear. No need to rewrite it in yet another way. But we're in territory of personal preference.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.