Other people have given good, correct answers but I want to be explicit about why, since it might not be obvious to some people (not directed at the OP).

A function is nothing more than a set of steps for the computer to take.

This is known as a function call:

getSmallestDivisor(121)

Anytime the return keyword is used, the function stops and replaces the function call with whatever comes after that return word (it could be nothing).

So in this case, the problem with the original function is that when the script reaches this line...

getSmallestDivisor(xSqrt);

...it returns 11 to that function call, which never gets returned to the original function call that happened inside of alert().

So the solution is simply to add a return before the one where it calls itself.

return getSmallestDivisor(xSqrt);

This is a common mistake when making recursive functions. A good way to help figure out what is going on is to make extensive use of the browser console.

function getSmallestDivisor(xVal) {    
    console.log("This is xVal: " + xVal);
    if (xVal % 2 === 0) {
        console.log("xVal % 2 === 0 was true");
        return 2;
    }
    else if (xVal % 3 === 0) {
        console.log("xVal % 3 === 0 was true");
        return 3;
    }
    else {
        console.log("This is else.");
        var xSqrt = Math.sqrt(xVal);
        console.log("This is xSqrt of xVal: " + xSqrt);
        if (xSqrt % 1 === 0) {
            console.log("xSqrt % 1 === 0 was true... recursing with xSqrt!!!");
            getSmallestDivisor(xSqrt);
        }
        else {
            console.log("This is the else inside of else. I am returning: " + xVal);
            return xVal;
        }
    }
}
var y = getSmallestDivisor(121);
console.log("This is y: " + y);

Now in your browser, you can open the console (Option + Command + I in most browsers on macOS) and watch what is happening - which parts get executed, etc.

Answer from Seth Holladay on Stack Overflow
Top answer
1 of 6
36

Other people have given good, correct answers but I want to be explicit about why, since it might not be obvious to some people (not directed at the OP).

A function is nothing more than a set of steps for the computer to take.

This is known as a function call:

getSmallestDivisor(121)

Anytime the return keyword is used, the function stops and replaces the function call with whatever comes after that return word (it could be nothing).

So in this case, the problem with the original function is that when the script reaches this line...

getSmallestDivisor(xSqrt);

...it returns 11 to that function call, which never gets returned to the original function call that happened inside of alert().

So the solution is simply to add a return before the one where it calls itself.

return getSmallestDivisor(xSqrt);

This is a common mistake when making recursive functions. A good way to help figure out what is going on is to make extensive use of the browser console.

function getSmallestDivisor(xVal) {    
    console.log("This is xVal: " + xVal);
    if (xVal % 2 === 0) {
        console.log("xVal % 2 === 0 was true");
        return 2;
    }
    else if (xVal % 3 === 0) {
        console.log("xVal % 3 === 0 was true");
        return 3;
    }
    else {
        console.log("This is else.");
        var xSqrt = Math.sqrt(xVal);
        console.log("This is xSqrt of xVal: " + xSqrt);
        if (xSqrt % 1 === 0) {
            console.log("xSqrt % 1 === 0 was true... recursing with xSqrt!!!");
            getSmallestDivisor(xSqrt);
        }
        else {
            console.log("This is the else inside of else. I am returning: " + xVal);
            return xVal;
        }
    }
}
var y = getSmallestDivisor(121);
console.log("This is y: " + y);

Now in your browser, you can open the console (Option + Command + I in most browsers on macOS) and watch what is happening - which parts get executed, etc.

2 of 6
29
if (xSqrt % 1 === 0) {
    return getSmallestDivisor(xSqrt); // missing return here
} else {
    return xVal;
}

Demo: Fiddle

🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Why function is returning undefined - Curriculum Help - The freeCodeCamp Forum
February 12, 2022 - Your function is just not returning the value. Return the value the expression (the math) evaluates to · The second console.log is supposed to log the function return value but the function just returns undefined (all functions do by default if no other return is given) · Now in-return it ...
Discussions

Why is my return returning undefined?
The bolded return in the for loop is exiting the loop at the first index before it can do anything. More on reddit.com
🌐 r/learnjavascript
12
3
May 7, 2024
Understanding Undefined Value returned from a Function in JS
I m stuck for a long time with that need help with explaning **Your code so far** // Setup let sum = 3; function addThree(sum) { return sum = sum + 3; } // Only change code below this line function addFive (sum) { sum +5 ; } // Only change code above this line addThree(); addFive(); **Your ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
15
0
March 10, 2022
JavaScript Functions , return undefined - Stack Overflow
Hello Everyone hope you all doing great , this is my code , function with name and callback taking the name to callback function to make return the name and console.log it if i function doSome... More on stackoverflow.com
🌐 stackoverflow.com
javascript function returns undefined instead of array values? - Stack Overflow
However this is not working as expected, and what ever i try it either returns undefined or not work at all, is it even possible to return a value from an event listener? If it is not, what kinda of alternatives do I have? Thanks in advance! ... Your outer function has no return statement. More on stackoverflow.com
🌐 stackoverflow.com
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript function returns undefined instead of value
JavaScript function returns undefined instead of value
April 25, 2023 - Typo in a variable name: If the function is returning an undefined variable, it’s possible that the variable name is misspelled or undefined. You have to check variable is defined and spelled correctly. Asynchronous code: If the function relies on asynchronous code, such as fetching data from an API, it may not return the expected value before the function completes. Make sure to use async/await or .then() to handle the asynchronous code. Incorrect data type: If the function is returning an incorrect data type, such as a string instead of a number, it may result in undefined.
🌐
Codecademy
codecademy.com › forum_questions › 50a66bb02a2b8cc47a000866
why does this return undefined ????? | Codecademy
When there is no identifier before a function call (i.e. obj.foo()) , JavaScript assumes it is being called by the global variable.
🌐
Reddit
reddit.com › r/learnjavascript › why is my return returning undefined?
r/learnjavascript on Reddit: Why is my return returning undefined?
May 7, 2024 -

Removing the return keyword will result in the outcome i want but i dont quite understand why adding a return to the code block will result in undefined?

function reverseArray(sentence){

let newArray=[]

for(let i= sentence.length-1; i >= 0; i--){

return

newArray.push(sentence[i])}

return newArray}

const sentence = ['sense.','make', 'all', 'will', 'This'];

console.log(reverseArray(sentence))

🌐
GuidingCode
guidingcode.com › home › how to fix javascript function returns undefined instead of value?
Fix JavaScript Function Returns Undefined Instead of Value
January 15, 2023 - Learn how to fix when a JavaScript function returns 'undefined' instead of a value with this guide covering reasons and corresponding fixes.
🌐
DevGenius
blog.devgenius.io › why-is-javascript-function-return-undefined-f519963d170c
Why is Javascript Function Return Undefined | by Evgeny Kirichuk | Dev Genius
October 20, 2022 - Developers often use it to log applications. And also in this console, you can write JavaScript code, which will be executed immediately. When I write the console.log(1) and press enter, the log output appears as expected. However, the next row shows undefined. Why do we have such a double output? That is because the developer tools console executes the code first and shows the returned value then. It works like that for all functions ...
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Understanding Undefined Value returned from a Function in JS - Curriculum Help - The freeCodeCamp Forum
March 10, 2022 - I m stuck for a long time with that need help with explaning **Your code so far** // Setup let sum = 3; function addThree(sum) { return sum = sum + 3; } // Only change code below this line function addFive (sum) { sum +5 ; } // Only change code above this line addThree(); addFive(); **Your browser information:** User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Challenge: Understanding Undefined Value returned fr...
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - Accessing a non-existing property of an object returns undefined. Accessing a out-of-bounds array element returns undefined. A function without a return statement or with a return statement but without an expression returns undefined.
Top answer
1 of 4
5

Your doSomething() function doesn't return anything, which means an assignment using it will be undefined. But, that's not really the problem here.

The underlying problem is that you seem to be mixing two different data processing patterns here: if you're writing purely synchronous code, then use returning functions (which immediately return some value). If you need asynchronous code, then use a callback (which will "eventually" do something). Mixing those two patterns is a recipe for problems and frustration:

Either:

  1. don't name your function a "callback", and have it return its processed value, or
  2. make the callback responsible for doing whatever it is you were going to do with val.

Case 1:

function doSomething(data, processor) {
  return processor(data);
}

function passThrough(v) { return v; }

var val = doSomething("test", passThrough);
// immediately use "val" here in for whatever thing you need to do.

Case 2:

function doSomething(data, callback) {
  // _eventually_ a callback happens - for instance, this
  // function pulls some data from a database, which is one
  // of those inherently asynchronous tasks. Let's fake that
  // with a timeout for demonstration purposes:
  setTimemout(() => callback(data), 500);
}

function handleData(val) {
  // use "val" here in for whatever thing you need to do. Eventually.
}

doSomething("test", handleData);

And if you want to go with case 2, you really want to have a look at "Promises" and async/await in modern Javascript, which are highly improved approaches based on the idea of "calling back once there is something to call back about".

2021 edit: a third option since original writing this answer is to use the async/await pattern, which is syntactic sugar around Promises.

Case 3:

async function doSomething(input) {
  // we're still _eventually_ returning something,
  // but we're now exploiting `async` to wrap a promise,
  // which lets us write normal-looking code, even if what
  // we're really doing is returning a Promise object,
  // with the "await" keyword auto-unpacking that for us.
  return someModernAsyncAPI.getThing(input);
}

function handleData(val) {
  // ...
}

async function run() {
  const data = await doSomething("test");
  handleData(data);
}

run();
2 of 4
2
function doSomething(name,callback) {
callback(name);
}

function foo(n) {
   console.log(n);
   return n;
}

var val = doSomething("TEST",foo);

Take a look at above code. When you call doSomething, which internally executes foo it prints on the console because thats what console.log is for. However, after this statement it returns n as well which then is received in doSomething. But its not being returned. To put it simply, what you are mainly doing is

function doSomething(name,callback) {
    const returnValue = callback(name);
}

If you call the above method, it will return undefined. To make it return correct value, you have to call "return returnValue". Similary you have to say return callback(name)

Hope this helps.

Happy Learning

🌐
Reddit
reddit.com › r/learnjavascript › console.log returns correct value. return returns undefined. why?
r/learnjavascript on Reddit: console.log returns correct value. Return returns undefined. Why?
August 20, 2021 -

I have a db, connected, I know it's pulling from the correct table. I'm trying to make a function that fetches the id of a city based on the name.

  function getCityId(inputCityName){
    con.query("SELECT * FROM event_cities", function (err, result, ) {
      if (err) throw err
      Object.keys(result).forEach(function(key) {
        let dbCityName = result[key]["city_name"].toLowerCase();
        var dbCityId = result[key]["city_id"];
        if (inputCityName == dbCityName){
          return dbCityId ;
** LINE ABOVE IS THE ISSUE
        }
      });
    });
    con.end();
  }
  
  let result = getCityId('toronto')
  console.log(result)

For the marker ** LINE ABOVE IS THE ISSUE

If I change that line to console.log(dbCityId), I get the correct number value. So, at the end, I'll just run let result = getCityId('toronto'). But, the moment I change that ** Line to

return dbCityId

And include

console.log(result)

at the end, I get undefined. I'm lost as to why. I need this function to return the value so that I can save it in a variable to later use in a query to save in the db.

Thoughts?

Top answer
1 of 5
4
The main problem is that conn.query is an asynchronous operation. If you're using callbacks, you can't directly return the result of that async task. The getCityId function should become asynchronous too by adding a second argument, that will be a callback function. Instead of returning dbCityId, you should invoke the callback. The function would look more or less like this: function getCityId(inputCityName, callback) { con.query("SELECT * FROM event_cities", function (err, result) { if (err) callback(err, null); // Replacing `.forEach` with a `for..of` loop // because we might need to stop the loop and // `.forEach` doesn't support that. for (const key of Object.keys(result)) { let dbCityName = result[key]["city_name"].toLowerCase(); var dbCityId = result[key]["city_id"]; if (inputCityName == dbCityName){ // Invoke the callback callback(null, dbCityId); // There's no need to keep looping // Let's stop the loop and the function return; } } // This will be executed if the city can't be found callback(null, null); }); con.end(); } getCityId("toronto", function(err, dbCityID) { console.log(`Toronto's ID is ${dbCityID}`); }); Does the environment you're working on support async/await and the Util.promisify method? If that's the case, you could transform getCityId to an async function and convert conn.query to Promises. That way you could return the ID: const util = require('util'); const promiseQuery = util.promisify(conn.query); async function getCityId(inputCityName) { const result = await promiseQuery("SELECT * FROM event_cities"); ... for (const key of Object.keys(result)) { ... if (inputCityName == dbCityName) return dbCityId; } }
2 of 5
2
That code doesn't run from top to bottom. That function that is passed to con.query is executed later in time when the data comes back the db. You need to handle the data inside of that function, console logging outside of it will not work. Goggle "async programming" to learn more about how this works.
🌐
Team Treehouse
teamtreehouse.com › community › why-is-my-code-returning-undefined
Why is my code returning undefined? (Example) | Treehouse Community
January 19, 2018 - So imagine this is the js console: function getDay() { return "Monday"' alert("Calculating day"); return "Friday"; } var dayOfWeek = getDay(): The response from the console is "undefined" rather than Monday - I wondered why (I'm obviously really new and trying to gain an understanding. Thanks again. ... I think I get it now. You're typing that whole thing into the console, and the console is returning "undefined" since there's no return value associated with the statement(s).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript - MDN Web Docs - Mozilla
A variable that has not been assigned a value is of type undefined. A function returns undefined if a value was not returned. Accessing a property that does not exist also returns undefined.
🌐
Nhanvietluanvan
nhanvietluanvan.com › trang chủ › javascript: troubleshooting undefined return value from a function
Javascript: Troubleshooting Undefined Return Value From A Function
July 7, 2023 - In conclusion, when a JavaScript function returns undefined instead of the expected value, it is essential to review the proper declaration and definition, check for misplaced or missing return statements, handle asynchronous operations correctly, validate variable declarations and assignments, use function arguments properly, address scoping issues, write conditional statements correctly, apply effective debugging techniques, and follow best practices.
🌐
Stack Overflow
stackoverflow.com › questions › 64673459
javascript - Why does function return undefined? - Stack Overflow
Because you're not hitting the while loop the function just exists and never returns a value. That is why you receive undefined.
🌐
EITCA
eitca.org › home › what happens if a javascript function does not include a return statement? what value is returned by default?
What happens if a JavaScript function does not include a return statement? What value is returned by default? - EITCA Academy
May 21, 2024 - If a function does not include a `return` statement, it does not mean that the function will not return a value; rather, it will return a predefined value by default. When a JavaScript function does not include a `return` statement, it implicitly returns `undefined`. This behavior is part of the JavaScript language specification and is consistent across all JavaScript environments, including browsers and server-side environments like Node.js.
🌐
javaspring
javaspring.net › blog › javascript-function-returning-undefined-value-in-nodejs
Why Does My JavaScript Function Return Undefined in Node.js? Troubleshooting Async Function Call Issues — javaspring.net
If you call an async function without await, the function returns a pending promise instead of the resolved value. If the caller doesn’t handle this promise, it may appear as undefined.