Bounce Falsy and the importance of the concept of Call back

Bounce Falsy and the importance of the concept of Call back
0

#1

Greetings! I just finished the challenge “Bounce Falsy” and after some discussion in the JavaScript chat, I decided I need to pose my question in the forums. I managed to make a somewhat clunky solution work:

function isNotFalsy(val) {
  return val;
}

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  var filteredArr = arr.filter(isNotFalsy);
  return filteredArr;
}

//debugger;
bouncer([7, "ate", "", false, 9]);

It worked… but it seemed “ugly” to me… Several Campers pointed out to me the much more efficient way:

arr.filter(function(i){return i;});

or even

arr.filter(Boolean)

People in the chat room kept mentioning “call back function” in their response to my ugly code… and it occured to me that … perhaps I should bring up the topic here. because So far in the lessons and challenges for freeCodeCamp I don’t really feel there has been much discussion or practice illustrating the use of call back functions!! What it is, How it works… why its important… It seems like a really important subject and concept for people learning the language. Does it not? I am wondering why this has not been covered more thoroughly?


#2

no one replied? Or am I not seeing the responses for some reason?


#3

@JeffGreenlee42,

callback functions are an important subject and are part of a programming paradigm called Functional Programming.
In short, functional programming lets you use functions as parameters so that you are able to pass them around as arguments to other functions.

The use of callbacks is used for many cases, but I’ll demonstrate one major case here.

Imagine you have a piece of code that always requests something from a server. Now, depending on the response from the server, you need to do a certain action. Because these calls to the server can take a long time or become erroneous, you do not want to either break your whole program or make your program wait.

To be able to do this and still not break the flow of your program, you can use Promises.

I won’t go into what promises are since that is a whole different subject, but what you need to know is that a Promise takes two callbacks functions as parameters. Why? Because the code you write inside a promise is executed asynchronously and only when a result is returned it invokes either the fulfilled callback or the rejected callback.

let myPromise =  new Promise(
    function (resolve, reject) {
         if(condition) {    // The condition here is an expression
             resolve();
       } else {
             reject();
      }
   })

Relating to the code you posted,

arr.filter(function(i){return i;}); 

The anonymous function(i) is a callback function which the filter method invokes on each element of the arr Array.

Hope that clarifies things a bit. You can read more about callback functions here: