What is closure in Swift? Is it similar to callback in Javascript?

In JavaScript, what are callbacks and what are its advantages?

  • In javascript, almost cases I write the function as the following: function jsFunc(param1, param2) {    ..... } But with javascript, you can code: function jsFunc(param1, param2, callback) {    var result = param1 + param2;    calback(result); } Then you call like this: jsFunc(1, 2, function(result){  console.log(result); }); Why does Javascript have "callback" concept and what are its advantages?

  • Answer:

    The term "callback" is used to describe a function declaration or expression * that is passed as an argument to another function, that is to be executed at some point within the function body of the enclosing function. The function's invocation generally follows some kind of computation where the results are passed as arguments to said function. * Any argument that the internal abstract operation IsCallable determines to be true can be used as a callbackFn. http://es5.github.com/#x9.11

Rick Waldron at Quora Visit the source

Was this solution helpful to you?

Other answers

described it very well. As an addition I would like to mention that it's also possible to use a function declaration as a callback. Here are a few examples of the usage: var foo = function (callback) { if (callback) { // execute callback if present callback(); } } // pass anonymous function expression on foo execution foo(function () { console.log('hello 1'); }); function callback() { console.log('hello from callback'); } // pass function declaration foo(callback); // hello from callback

Michal Kuklis

Good answers here already. If you still are confused, this article might help, I liked the very friendly way it explains callbacks: http://recurial.com/programming/understanding-callback-functions-in-javascript/

Anonymous

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.