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?

Answer from chiliNUT on Stack Overflow
Top answer
1 of 12
183

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 12
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.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript - MDN Web Docs - Mozilla
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!"
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Returning undefined - JavaScript - The freeCodeCamp Forum
March 21, 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…
🌐
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))

🌐
Cloudinary
cloudinary.com › home › why does javascript sometimes return “undefined”?
Why does JavaScript sometimes return "undefined"?
November 14, 2025 - For reliable hosting, caching, and consistent delivery patterns that reduce undefined or broken media references, review this guide on understanding image hosting for websites. ... undefined means no defined value: missing returns, absent ...
🌐
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 - 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.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript undefined
JavaScript undefined
October 6, 2023 - const add = (a,b) => { return; a + b; };Code language: JavaScript (javascript) That’s why you get the undefined as the return result.
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › javascript-check-if-undefined-how-to-test-for-undefined-in-js
JavaScript Check if Undefined – How to Test for Undefined in JS
November 7, 2024 - In case you are in a rush, here are the three standard methods that can help you check if a variable is undefined in JavaScript: if(myStr === undefined){} if(typeof myArr[7] === "undefined"){} if(user.hobby === void 0){} Let’s now explain ...
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript - Dmitri Pavlutin
March 23, 2023 - Adding a default value to parameter ... to set default values for optional parameters. Implicitly, without return statement, a JavaScript function returns undefined....
🌐
Sandromiguel
sandromiguel.com › home › snippet › returning undefined (javascript)
Returning undefined (JavaScript) – Coding is Awesome
November 25, 2020 - const funcA = () => {}; const funcB = () => { return; }; const funcC = () => { return undefined; }; console.log("funcA returns", funcA()); // funcA returns undefined console.log("funcB returns", funcB()); // funcB returns undefined console.log("funcC returns", funcC()); // funcC returns 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.
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

🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-map-returns-undefined
map() method returns undefined in JavaScript [Solved] | bobbyhadz
The map() method returns undefined values when we forget to explicitly return a value in the callback function we passed to the method.
🌐
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.
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

🌐
Medium
medium.com › coding-at-dawn › how-to-check-for-undefined-in-javascript-bcedd62c8ad
How to Check for Undefined in JavaScript | by Dr. Derek Austin 🥳 | Coding at Dawn | Medium
January 4, 2023 - Variables that have not been declared ... not throw a ReferenceError. The typeof keyword will return "undefined" for undeclared variables as well as for any variable containing the value undefined....
🌐
Medium
vvkchandra.medium.com › essential-javascript-mastering-null-vs-undefined-66f62c65d16b
Essential JavaScript: Mastering null vs undefined | by Chandra Gundamaraju | Medium
September 9, 2020 - In summary, function parameters are initialized with the default values only when a parameter has a missing value or primitive value undefined is passed in explicitly. A JavaScript function can take zero or more inputs, and it can optionally return an output back to the function’s caller.
🌐
CodeBurst
codeburst.io › javascript-what-is-the-return-statement-97d8b11a1a0c
JavaScript: What is the return statement? | by Brandon Morelli | codeburst
August 21, 2017 - As you can see, our explicitly returned true value replaces the default undefined value.
🌐
IQCode
iqcode.com › code › javascript › js-this-returns-undefined
js this returns undefined Code Example
function foo() { console.log(this); } // normal function call foo(); // `this` will refer to `window` // as object method var obj = {b...