Why Does My Function Return Undefined Whilst I Do Give It an Argument

Why does my function return undefined whilst I do give it an argument

Please believe me, previous answer was the correct way to go, but if you want to try your own flow, then here is a solution, it will be slower, many unwanted variables, so much coding, etc. you can play with code from jsbin

// declare global
// getting form by id (jquery),
// it is always good practise to define your element in global scope
// we used $somename for jquery specific names
// remember $('somekelement') is a heavy function of jQuery
// which did lots of calculation behind the scene
// this is why i am declaring it only once
// it will help me to not used $('#myform') every time, need to access form
var $myform = $('#myform');

// for your logic i wanted two extra boolean to check if my password and confirm_password i created or not.
var isPassword = false; // by default not created
var isConfirmPassword = false; // false means not created true means created.

// this is your function that create a input and some logic as per your requirements
function getPassword() {

if(!isPassword) {
let pwd = $('<input/>', {
}).on('blur', function() {

if(false) {
//more unrelated code
} else {
'color': 'gray',
'border': '1px solid green'
let cValue = $(this).val();

console.log("Your cValue: "+ cValue); // here you are getting your values right.

let x = getPasswordConfirm(cValue); // here you are calling another function that generate another input
return pwd;
isPassword = true;

// if this function is generating new input, then it must not be called inside of getPassword function, because blur event may occur multiple times and each blur will create new confirm_password fields
// here i think logically not possible,
// only possible way here is to distribute your coding into two section
// 1st section will build all your dynamic input fields
// 2nd section will validate your inputs.
function getPasswordConfirm(cValue) {
window.cValue = cValue; // i saved cValue here in global namespace so next time.
console.log('argument cValue: '+cValue); // wola, you got the value here.

// but sadly, you didn't have c_pwd yet, so you couldn't be able to fire blur event here.
// Your blur event will be created but if will fire on out of focus, but next time cValue will not be passed
// because it will happened only one time or you will have multiple inputs each trying to catch a event before born to the world
if(!isConfirmPassword) {
let c_pwd = ($('<input/>', { // changed name to c_pwd
'placeholder':'Confirm Password'
})).on('blur', function() {
console.log('What was cValue: '+ window.cValue);
if(false) {
//unrelated code
} else {
if ($(this).val() !== cValue) {
console.log('====rock you got cValue here : '+cValue); // getting this value here as well. but problem is that you are getting multiple inputs
//this is where it goes wrong, cValue is undefined???
} else {
'color': 'gray',
'border': '1px solid green'
}.bind(this)); // you can also bind your subscope to their parent scope by bind funciton, in new ES6 we create arrow function (arg1, arg2) => {console.log(arg1,arg2);}

isConfirmPassword = true;

//return c_pwd; // comment this line and uncomment next line see result by yourself.
$myform.append(c_pwd); // i am appending confirm_password input on blur on password result will create multiple confirm boxes


// suppose your two function build your form then code for appending will be like that

Why do functions return `undefined` instead of `null` by default?

The specification says of null and undefined:

undefined value

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

null value

primitive value that represents the intentional absence of any object value

undefined represents a failure to assign a value. It is the total absence of a value. null represents the positive assertion of a non-value in an object context. null is intended to be used when an object is expected but the current value is no-object.

Given these two definitions, it seems obvious that undefined is the correct choice, since

  1. functions can return values other than objects, and
  2. a failure to specify a return value maps neatly onto a failure to assign a value

Javascript function returning 'undefined'

Remove the outer [] array of the Object.values. Object.values already returns values in array.


var values = [Object.values(gradeDict)];


var values = Object.values(gradeDict);

working example:

function my_index(arr, score) {
for (const [index, elem] of arr.entries()) {
if (elem.includes(score)) {
return index;

function getGrade(score) {
let grade;
var gradeDict = {
A: [26, 27, 28, 29, 30],
B: [21, 22, 23, 24, 25],
C: [16, 17, 18, 19, 20],
D: [11, 12, 13, 14, 15],
E: [6, 7, 8, 9, 10],
F: [0, 1, 2, 3, 4, 5],
var keys = Object.keys(gradeDict);
var values = Object.values(gradeDict);
grade = keys[my_index(values, score)];

return grade;


Why the function argument returns undefined when using props?

When working with arrow function, you need to call like,

<Buttons selectReport={() => this.onSelect} > //without parenthesis

also setState is async so you need to use callback in setState to print value.

You need to do this,

export default class Ind extends Component {
this.state = { report: null}
onSelect = (newreport) => {
console.log("Parameter: ", newreport)
report: newreport
},()=> console.log("State: ", this.state.report)) //prints in callback

<Buttons selectReport={() => this.onSelect}>

Why does this function returns undefined?

The reason you get undefined is because the function isThree() doesn't return anything. The two returns in your function return from the anonymous function inside foreach().

I think your function tries to determine if there's a value 3 in the array. There is already a function for that: includes(). Your function could be:

function isThree(...args) {
return args.includes(3);


Is it better to return `undefined` or `null` from a javascript function?

I will argue there is no best way, and even standard functions sometimes choose one or the other.

For example:

  • [[Prototype]]

    Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using null.

  • Object.getOwnPropertyDescriptor

    It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using undefined.

  • document.getElementById

    It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using null.

So just choose whatever you prefer or think makes more sense for your specific case.

Function Returns undefined object

Because the getStats function isnt returning anything, only the function which is an argument of fs.readFile returns.

Here I have made a callback argument, so that you can do what you need with everyStats inside of a callback function.

var getStats = function (callback){
fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
everyStats = JSON.parse(data);


getStats(function(stats) {
// do what you want with stats

Why does this recursive function return undefined?


The problem is that you don't return the recursive call's result, thus it is undefined when the whole call to merge is resolved.

Let me take you through the execution, step-by-step:

  1. With arguments "AAA" and "BBB", their lengths are not 0, go to else. Once in else, str3 is "AB", call merge("AA", "BB").
  2. With arguments "AA" and "BB", their lengths are not 0, go to else. Once in else, str3 is now "ABAB", call merge("A", "B").
  3. With arguments "A" and "B", their lengths are not 0, go to else. Once in else, str3 is now "ABABAB", call merge("", "").
  4. With empty string arguments, length is 0. Now go to the if statement, where str3 is logged, and returned.
  5. Since the merge("", "") call has resolved (to "ABABAB" as it is returned), we continue where we left off in the call merge("A", "B"), thus going "up" the call stack.
  6. We start where we left off in call merge("A", "B"), in the else branch. There are no more statements or expressions in that call, so it's resolved. There are no return statements, so by default it returns undefined. We go "up" the call stack to call merge("AA", "BB") where we left off.
  7. We start where we left off in call merge("AA", "BB"), in the else branch. There are no more statements or expressions in that call, so it's resolved. Again, there are no return statements so by default it returns undefined. We go "up" the call stack to call merge("AAA", "BBB") where we left off.
  8. We start where we left off in call merge("AAA", "BBB"), in the else branch. There are no more statements or expressions in that call, so it's resolved. Again, there are no return statements so by default it returns undefined. There are no more calls, so everything's resolved - and merge("AAA", "BBB") returns undefined.

TL;DR: The recursive call is not returned on each call in the else branch, so the value of str3 is returned to the call merge("A", "B"). The call merge("A", "B") does not return anything, it returns undefined. The same goes for all other calls - they have no return statement in the else branch so undefined is returned. When all calls are resolved, undefined is returned.


The solution is to simply prepend return to your recursive calls. That way, the result of each call would be returned, 'delegating' the final returned value of str3 up the call stack - the call returns "ABABAB", not undefined.

Since we now return the result of the call, steps 6, 7, and 8 above now have a return statement. That means we don't return undefined, but instead str3. This is because merge("", "") returned "ABABAB", which is the value of str3. That result is then returned in call merge("A", "B") because of the new added return statement, which is then returned in call merge("AA", "BB"), and so on, until the call is completely resolved, and the returns the value of str3.

Here's the new code:

var str3 = "";function merge(str1, str2) {    if(str1.length == 0 || str2.length == 0) {        console.log(str3);        return str3;    } else {        str3 = str3 + str1.substring(0, 1) + str2.substring(0, 1);        return merge(str1.substring(1, str1.length), str2.substring(1, str2.length)); //we return the recursive call    }}
var mergedString = merge("AAA","BBB"); //mergedString is "ABABAB"

Why is the first argument of reduce() returning undefined?

The callback you pass to .reduce() needs to return the cumulative value (the value that will be passed as prev to the next iteration of the loop. Since you are returning nothing, you get undefined for the next iteration of your loop.

This complicates what you're trying to do because you are trying to keep track of two values in your loop. As such, you would either have to avoid using prev at all or you'd have to make it be a data structure that had both your values in it. Your use is not a textbook example for .reduce(). Your code is probably simpler with an iteration using .forEach() or for/of.

function countPositivesSumNegatives(input) {
let countPositive = 0;
let sumNegative = 0

if (!input || input.length === 0){
return [];
} else {
if (num > 0) {
} else {
sumNegative += num;
return [countPositive, sumNegative];

Related Topics

Leave a reply