Tutorial by Examples

Callbacks offer a way to extend the functionality of a function (or method) without changing its code. This approach is often used in modules (libraries / plugins), the code of which is not supposed to be changed. Suppose we have written the following function, calculating the sum of a given array ...
This is a normal function call: console.log("Hello World!"); When you call a normal function, it does its job and then returns control back to the caller. However, sometimes a function needs to return control back to the caller in order to do its job: [1,2,3].map(function double(x) {...
Callbacks can be used to provide code to be executed after a method has completed: /** * @arg {Function} then continuation callback */ function doSomething(then) { console.log('Doing something'); then(); } // Do something, then execute callback to log 'done' doSomething(function () ...
Callbacks are often used to provide error handling. This is a form of control flow branching, where some instructions are executed only when an error occurs: const expected = true; function compare(actual, success, failure) { if (actual === expected) { success(); } else { failure...
Often when using a callback you want access to a specific context. function SomeClass(msg, elem) { this.msg = msg; elem.addEventListener('click', function() { console.log(this.msg); // <= will fail because "this" is undefined }); } var s = new SomeClass("hello&q...
Using arrow function as callback function can reduce lines of code. The default syntax for arrow function is () => {} This can be used as callbacks For example if we want to print all elements in an array [1,2,3,4,5] without arrow function, the code will look like this [1,2,3,4,5].forEach...

Page 1 of 1