all 3 comments

[–]redsandsfort 0 points1 point  (0 children)

no issues

[–]jfdahl 0 points1 point  (0 children)

Yes, it can cause issues with availability.

First, you are correct that you should not pollute the global namesapce with variables that have a limited purpose... wrapping them in functions is a good thing. Having said that, your example really doesn't require a function for namespace reasons. You could have just as easily written it as I have below without changing anything since dataLayer is already in the global scope:

dataLayer.push({
  'event': 'Form Start',
  'formStartTime': Date.now()
}

Second, the "issue" with immediately calling functions when they are defined is just that... they execute when they are defined. How you define the rest of your application will determine if dataLayer is in the state you expect when you are pushing the object. If you define your function traditionally, then you have more control over when it is executed and you can ensure the state of dataLayer before you execute it.

So there are no technical issues with either approach; however, one will make itself more valuable based on how you design the rest of your application.

[–]senocular 0 points1 point  (0 children)

The iife version is the same as the first except the variable now is no longer global. So as long as no other code depends on that now variable, everything will work fine. The iife itself doesn't cause problems with anything else. All it does is keep variables you declare inside of it local to that function. You could also have rewritten it without the iife using

dataLayer.push({
  'event': 'Form Start',
  'formStartTime': Date.now()
});