5

I am looking at some code, and I see that it is written as shown below. It doesn't make sense to me. Is it wrong? Why is it written like that? Also, shouldn't the use strict; go at the very top, outside of the code?

(function() {
  'use strict';
  angular.module('itemList', [])
    .component('itemList', {
      templateUrl: 'item-list/item-list.component.html',
      controller: ['Item', ItemController]
  });

  function ItemController(Item) {
    //code
  }
}());
user3152131
  • 543
  • 3
  • 7
  • 18

2 Answers2

5

The reason it is wrapped in an IIFE is to keep all declarations like "use strict", functions and variables local to the scope contained within and not set in global namespace

If "use strict" was set global it can affect other unrelated code that my not comply and thus would cause unexpected errors to be thrown

Is it wrong to define controller in...

No. It is a best practice

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

It is an "immediately-invoked function expression". The main advantage is to make sure you don't pollute the global namespace when declaring local variable.

var someLeakingVar;

function foo(){
  //do something with someLeakingVar.
}

The problem with the construct above is that any script coming after will be able to reach/modify someLeakingVar.

If you wrap it within the IIFE. You are sure, only the code within the expression is able to reac/modify it

(function(){
  var nonLeakingVar = 'foo';
  //...
})()
//here nonLeakingVar is undefined

In the same way as the 'use strict' statement can be function scoped, you make sure only the code within the IIFE will run in strict mode.

You can find more details:

  1. strict mode
  2. IIFE
Community
  • 1
  • 1
laurent
  • 2,590
  • 18
  • 26