Because that is exactly what you are telling it to do. You tell it to return console.log (x/2). First it has to evaluate that to get its return value. In the process of evaluating it, it logs it to the screen. Then, since console.log doesn’t return anything, it effectively returns undefined. So, si… Answer from kevinSmith on forum.freecodecamp.org
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript | MDN
The undefined global property represents the primitive value undefined. It is one of JavaScript's primitive types. function test(t) { if (t === undefined) { return "Undefined value!"; } return t; } let x; console.log(test(x)); // Expected output: "Undefined value!"
🌐
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.
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

🌐
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.
🌐
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.
🌐
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 and even for the variables’ assignment.
Find elsewhere
🌐
Team Treehouse
teamtreehouse.com › community › why-is-my-code-returning-undefined
Why is my code returning undefined? (Example) | Treehouse Community
December 17, 2017 - 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).
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

🌐
Quora
quora.com › Why-does-the-variable-return-Undefined-when-implementing-a-function-on-a-class-in-JavaScript
Why does the variable return 'Undefined' when implementing a function on a class in JavaScript? - Quora
Answer (1 of 4): The variable doesn’t return anything. But I suspect your code is something like this [code]function foo() { .... return something } const bar = foo() // bar is undefined [/code]In that case your “something” is being set to undefined somewhere/somehow in your function.
🌐
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.
🌐
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.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Returning undefined - JavaScript - The freeCodeCamp Forum
February 15, 2019 - Tell us what’s happening: I am supposed to, “Modify the function abTest so that if a or b are less than 0 the function will immediately exit with a value of undefined.” but when I do the code one way it returns two values undefined and when I switch it around then everything runs but not the undefined.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - The add() function will look like the following to the JavaScript compiler: const add = (a,b) => { return; a + b; };Code language: JavaScript (javascript) That’s why you get the undefined as the return result. When you access an array element that is out-of-bounds, you’ll get the undefined value...
🌐
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.
🌐
W3Schools
w3schools.com › js › js_mistakes.asp
JavaScript Mistakes
const person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; person.length; // person.length will return 3 person[0]; // person[0] will return "John" Try it Yourself » · In JavaScript, objects use named indexes. If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object. After the automatic redefinition, array methods and properties will produce undefined or incorrect results:
Top answer
1 of 11
180

Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.

From the ECMAScript2015 spec

4.3.10 undefined value

primitive value used when a variable has not been assigned a value

4.3.12 null value

primitive value that represents the intentional absence of any object value

http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type

Further reading:

When is null or undefined used in JavaScript?

2 of 11
88

I will give you my personal opinionated way of choosing between the two.

My simple question is: could the value, given another input/state/context be defined to something?

If the answer is yes then use null else use undefined. More generally any function returning an object should return null when the intended object does not exist. Because it could exist given another input/state/context.

null represents the absence of value for a given input/state/context. It implicitly means that the concept of the value itself exist in the context of your application but may be absent. In your example the concept of a next card exists but the card itself may not exist. null should be used.

undefined implicitly represents the absence of meaning of that value in your application's context. For example, if I manipulate a user object with a given set of properties and I try to access the property pikatchu. The value of this property should be set to undefined because in my context it doesn't make any sense to have such a property.