Why are javascript callbacks passed as arguments?

  • A+
Category:Languages

I'm trying to understand callbacks for the first time. In all the examples I have seen, callbacks are always passed as arguments. Here's a common example:

let result = 0;  function add(num1, num2, callback) {     setTimeout(() => {         result = num1 + num2;         callback();     }, 2000); }  function logResult() {     console.log(result); }  add(4, 5, logResult); // here's the callback passed as argument 

The same result can be obtained with following code. And it doesn't need callback to be passed as an argument.

let result = 0;  function add(num1, num2) {     setTimeout(() => {         result = num1 + num2;         logResult();     }, 2000); }  function logResult() {     console.log(result); }  add(4, 5); 

Is it just for readability and understanding code better that they are passed as arguments ? Or is there something that I'm missing? Please can somebody enlighten me ?

 


You don't need a callback at all in your example, you could just do:

function add(num1, num2) {   setTimeout(() => { // thats a callback too, just saying ...     const result = num1 + num2; // don't leak variables, declare them!     console.log(result);   }, 2000); } 

However programming is all about creating reusable codes, that can then be composed into more complex programs. Therefore you don't want to limit the usage of add to logging the result, instead you can achieve various tasks with it if you accept a callback:

 add(1, 2, (result) => {    add(result, 5, (result2) => {     alert(result2);    }); }); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: