r/learnjavascript • • Feb 03 '21

Callback functions in JavaScript

https://jscurious.com/callback-functions-in-javascript/
3 Upvotes

5 comments sorted by

4

u/ninoninoninous Feb 03 '21

I tried to leave a comment on your blog but I don't think it worked correctly. So...

In reference to this code...

function takeOrder() {
    setTimeout(() => {
       return (Math.random() * 10) <= 5 ? 'Coffee' : 'Tea';
    }, 1000);
}

let order = takeOrder();
console.log('Order is for: ' + order);
// Order is for: undefined

...you say:

Here the takeOrder function returning some value after 1 second and by that time the console.log statement has already executed therefore printed value of order as undefined.

This explanation is not good. The actual problem with that code is not the order of execution. The problem is that "takeOrder function returning some value after 1 second" is false. the takeOrder function is returning nothing at all. And that's why the value of order is undefined. Returning from the function inside the setTimeout does not mean returning from takeOrder.

If the problem was the order of execution, you could just put the console.log inside another, longer setTimeout and it would print the value correctly. But this isn't the case. Even if you did that, order would still be undefined.

1

u/lemonizer Feb 03 '21

This is correct but the statement "the takeOrder function is returning nothing at all" is not entirely accurate. When a function does not have a `return` statement specified, it will return the primitive value of `undefined`.

2

u/ninoninoninous Feb 03 '21

If one wanted to be extremely pedantic about it, they could say the function still returns nothing, and that it's the JavaScript engine that returns the undefined when the result of executing the function produces no value.

But that would be really pedantic and doesn't really help anyone much, does it?

0

u/[deleted] Feb 03 '21

[deleted]

3

u/ninoninoninous Feb 03 '21 edited Feb 03 '21

And if one were to do that they could just search for 9.2.1 [[Call]], step 11, and see that it's the engine doing it.

But, again, is all this really necessary?