%% date:: [[2022-12-25]] %% # [[Function returns undefined in js]] So you've got a [[JavaScript]] function (A) that calls a different function (B) that returns a value, like this: ```js function A() { let processedResult = B(stuff); console.log(processedResult); } function B(input) { // Processing here, like sending an HTTP request and saving the response. let result = input + someOtherStuff(); console.log(result); return result; } ``` In `B()`, you see that `result` is displayed with a value. However, when `B()` is called by `A()`, the returned value, `processedResult`, seems to be `undefined`. Why?? ## Cause One reason why this might have happened is that `B()` contains code that hadn't quite finished by the time the value was assigned. JavaScript code runs sequentially by default, so by the time `B()` logs the result, it will have a value. However, `A()` may not yet have received the right value, but still proceeds to assign `processedResult` the value of `undefined`. ## Solution ### Use [[Callbacks in js]] A callback is an argument in a function that is in itself another function. [^w3] For example, you could do something like this: ```js function A() { B(stuff, function(outputOfB) { // This changed let processedResult = outputOfB; // This changed console.log(processedResult); }); } function B(input, callback) { // This changed // Processing here, like sending an HTTP request and saving the response. let result = input + someOtherStuff(); console.log(result); callback(result); // This changed } ``` In the revised code above, instead of `return()`, you're now using `callback()`, which is like saying "When you do `B()`, do all the steps, but only return `result` when everything has been finished". For example, if there was an HTTP request in `B()`, the code will not just *send* the request and move onto the next line; it'll actually wait for a response before proceeding. Then, in `A()`, the `console.log()` statement won't be activated until all arguments are passed to it, including the result of `B()`. ### Consider using [[Asynchronous functions in js]] [^w3]: W3 Schools. _JavaScript callbacks._ Retrieved from https://www.w3schools.com/js/js_callback.asp