g4g4
g4g4

Reputation: 59

JavaScript: output of a function which returns a string outputs "undefined". Why that?

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));
  });

Upvotes: 0

Views: 36

Answers (1)

g4g4
g4g4

Reputation: 59

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));
  });

Upvotes: 1

Related Questions