0

As I know that

'Any function that is passed as an argument is called a callback function'

, and also that if the callback function takes some time to complete, the statements followed by this callback function will run. Here is example about using callback in array.filter() from MDN:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

My question is why I can get console.log(result) output immediately, and instead of 'undefined' or something?

Does it mean the callback used inside the Array.prototype.filter() can compete very fast. Only those callbacks which take some time like download things, reading files, talking to database, etc. (readFile('example.text) may have undefined result value, shown in this example?

James Z
  • 12,209
  • 10
  • 24
  • 44
juanli
  • 583
  • 2
  • 7
  • 19
  • Possible duplicate of [Understanding the Event Loop](https://stackoverflow.com/questions/21607692/understanding-the-event-loop) – Matt Morgan Mar 11 '18 at 11:17

1 Answers1

1

Array#filter method is not asynchronous in nature, it means "callback" function does not wait for any kind of IO or Network calls.

In Filter method, provided function(callback) is to test whether values pass the given criteria or not.

If you go through the docs, it says -

callback - "Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise"

Rayon
  • 36,219
  • 4
  • 49
  • 76