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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With