user3195250
user3195250

Reputation: 127

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!!!

Upvotes: 1

Views: 52

Answers (1)

danbal
danbal

Reputation: 1531

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

Upvotes: 3

Related Questions