iAteABug_And_iLiked_it
iAteABug_And_iLiked_it

Reputation: 3795

Is it necessary to use nested functions in javascript?

Forgive me if this is a basic question but I come from a desktop c# background and this javascript nested functions pattern seems a bit odd to grasp. This isn't strictly related to angular, more of a javascript question. It seems that on tons of sites/tutorials nested functions are heavily used,

HTML

<div ng-controller="MyController">
  <button ng-click="sayHello()">Hello</button>
</div>

For this contrived example, when this button is clicked, it will show a hello world message

function MyController($scope) {
    $scope.sayHello =function sayhello(){
    alert("hello world");
};

However , we could just as easily separate the inner function to make the script easier to read, like so

var sayHelloVariable = function sayhello() {
    alert("hello world");
};

function MyController($scope) {
    $scope.sayHello = sayHelloVariable;
};

For this simple example we only have a few lines but I have seen tutorials with lines upon lines of nested functions making it hard to understand what is going on ( or perhaps I will come around to javascript way of thinking in time?)

Is there a particular reason why nesting functions is so popular, perhaps a performance reason?

Thanks

Upvotes: 1

Views: 127

Answers (1)

SgtPepper43
SgtPepper43

Reputation: 544

With angular, unless you need to reuse that function, any functions relating to that controller are best defined inside that controller, as in the first example. It's better not to pollute the parent scope with tons of random functions. Think of the function MyConroller($scope) more as a class definition than as a function definition.

Upvotes: 1

Related Questions