Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Functions Inside Parameters?

I come from a background in C/C#/Java and PHP so I'm used to those standards of coding, where a function is defined using function(parameters) { ... return x}

But lately I've been learning some JS libraries like Angular/Node and come across functions (or maybe there not?) with another function inside the parameters, like this:

app.controller('MainController', ['$scope', 'forecast', function($scope,     forecast) {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);

app.factory('forecast', ['$http', function($http) { 
return $http.get('https://s3.amazonaws.com/codecademy-    content/courses/ltp4/forecast-api/forecast.json') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        }); 
 }]);

It just confuses me and goes against what I've learned about functions. Is this convention only used in scripting languages? I seems like they go

function(parameter, function(parameter) { do something; }); 

Anyone explain why this is used or if it does anything than a normal function?

Thanks.

like image 286
JimmySmithJR Avatar asked Feb 04 '26 18:02

JimmySmithJR


1 Answers

In Javascript a variable can return a function, which could return another function, pretty much endlessly.

For example:

var myFunction = function() {
    return getAnswer();
}

var getAnswer = function() {
    return "Hello world!";
}

console.log(myFunction); will return

var myFunction = function() { return getAnswer(); }

and console.log(myFunction()); will return

"Hello world!"

So App.controller is a variable that is part of the app object, but it's a function so you are passing in parameters, some of which can be a function.

https://jsfiddle.net/Lu46sf2v/2/

like image 151
Justin Avatar answered Feb 06 '26 08:02

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!