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.

🌐
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 values undefined and when I switch it around then everything runs but not the undefined.
Discussions

Why function is returning undefined
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 ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
February 12, 2022
javascript - Simple function returning 'undefined' value - Stack Overflow
I have checked how many times the recursive calls happened; they actually happened two times. I logged the values of xVal in those two different calls, and they display 121 and 11. I am really confused here about why this function is currently returning undefined. More on stackoverflow.com
🌐 stackoverflow.com
Why is my code returning undefined?
Lucille Fox is having issues with: I am not grasping this lesson and in trying to understand it, I am running all the examples and questions through the console. But rather than r... More on teamtreehouse.com
🌐 teamtreehouse.com
2
January 19, 2018
How to avoid returning undefined from a function that catches error?
What do you expect it to return if there's an error? It's returning undefined because it's erroring out. More on reddit.com
🌐 r/typescript
35
0
November 14, 2023
🌐
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!"
🌐
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

🌐
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
🌐
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.
🌐
Team Treehouse
teamtreehouse.com › community › why-is-my-code-returning-undefined
Why is my code returning undefined? (Example) | Treehouse Community
January 19, 2018 - The reason why the console is returning undefined is because no value is being returned explicitly.
🌐
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 each of these methods in more detail. One of the first methods that comes to mind is direct comparison. This is where you compare the output to see if it returns undefined.
🌐
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.
🌐
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 ... use it to set default values for optional parameters. Implicitly, without return statement, a JavaScript function returns undefined....
🌐
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.
🌐
Reddit
reddit.com › r/typescript › how to avoid returning undefined from a function that catches error?
r/typescript on Reddit: How to avoid returning undefined from a function that catches error?
November 14, 2023 -

I have several functions, which throws errors. What I found frustrating, is that the function would return undefined, if there is no return statement after catch clause, and in the future call stack I should handle the undefined value. Although it makes sense to be so, can this be avoided somehow? If not, can somebody explain me why this can not be avoided?

For example, I have this function:

export function parseStringToFormat(
    initialDateStr: string,
    initialDateFormat: string,
    desiredFormat: string,
    referenceYear: number
): string {
    try {
        const initialDateFormatParts: DatePart[] = computeFormatParts(initialDateFormat);
        const initialDateNumbers: EditDateNumbers = computeDateNumbers(initialDateStr, initialDateFormatParts, referenceYear);

        const separatorIndex: number = initialDateStr.search(ALLOWED_SEPARATORS_PATTERN);
        const separator: string = initialDateStr[separatorIndex];
        const formatParts: DatePart[] = computeFormatParts(desiredFormat);
        const finalDateStr: string = computeStringBasedOnNumbers(initialDateNumbers, formatParts, separator);

        return finalDateStr;
    } catch (e: unknown) {
        console.error(e);
    }
}

And any of the used function within it can throw errors.

Obviously, the IDE tells me that the function does not include undefined in its return type.

Thanks!

🌐
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
🌐
Bitstack
blog.bitsrc.io › why-does-console-log-return-undefined-e06d44b4d0f8
Why does console.log() return 'undefined'? | Bits and Pieces
March 16, 2022 - With our new understanding of what REPLs are and how they work we can work through the process of console.log(“Hello, Daniel!”). First, the REPL will read in our command as JavaScript. Then it will look to evaluate parts of our command. The evaluate step will always return something, like the sum of 2 + 2 or a modified array, but in this case there is nothing to evaluate. Therefore it returns undefined.
🌐
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))