0

console.log in the function "getNameByDate" will produce "Ben" and "Tom". But the other console.log outside of the function will produce "undefined". Why not the same output?

  let arr = [
    {
      databaseObject: { geburt: "24.01.2012", name: "Ben"}
    }, 
    {
      databaseObject: { geburt: "29.02.2012", name: "Tom"}
    }, 
  ];

  function getNameByDate(date) {
    jQuery.each( arr, function( i, val ) {         
      if ( val.databaseObject.geburt == date ) {
        console.log (val.databaseObject.name);        
        return val.databaseObject.name;
      }
    });
  }

  let dates = ["24.01.2012", "29.02.2012"];

  jQuery.each( dates, function( i, val ) {
    console.log(getNameByDate(val));
  });
1
  • 1
    You are forgetting that function (i, val) ... is also a function and the return inside it belongs to function (i, val) ... not getNameByDate(). The function getNameByDate() returns nothing which in javascript is the same as undefined Commented Jun 12, 2019 at 19:13

1 Answer 1

1

Returning the result in the jQuery.each-loop was not correct. Instead we have to assign the result in that loop to a variable, break the loop by returning false and return the variable after the loop:

 let arr = [
    {
      databaseObject: { geburt: "24.01.2012", name: "Ben"}
    }, 
    {
      databaseObject: { geburt: "29.02.2012", name: "Tom"}
    }, 
  ];

  function getNameByDate(date) {
    var friendsName;
    jQuery.each( arr, function( i, val ) {         
      if ( val.databaseObject.geburt == date ) {
        console.log (val.databaseObject.name);
        friendsName = val.databaseObject.name; 
        return false; // exit loop
      }
    });
    return friendsName;
  }

  let dates = ["24.01.2012", "29.02.2012"];

  jQuery.each( dates, function( i, val ) {
    console.log(getNameByDate(val));
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively you can also replace jQuery.each() with a for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.