简体   繁体   中英

Javascript: call a function to return a value from within a function?

Bit complicated to phrase but I have one function that needs to call another one to get a value returned to use in the first function - an example:

The first function needs to get the variable gameTitle from the function getGameInfo()

function getGameInfo(){
     var gameTitle = "test game";

    if(gameTitle){
        return gameTitle;
    }else{
        return undefined;
    };

};

function getImages(){

    var gameTitle = getGameInfo();
     console.log(getGameInfo());

};

but for some reason this never works - it always returns "undefined" - I am extremely confused why this is happening

EDIT: I was given an answer in the comments by Pointy - this was not my whole code as this was an example but I was using an asynchronous API and was trying to get the function to return a value from an callback hence the issue of undefined!!!

getValue returns correctly, so I assume your problem is that testFunction returns undefined . It is because you didn't specify it what to return, you only told it to print something on the console. If you also want it to return something, add a return statement to it.

function testFunction(){

  var newValue = getValue();
  console.log(newValue);
  return newValue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM