RecodeAlan RecodeAlan - 10 months ago 67
Javascript Question

JS : why isn't this value passing from one function to another?

Further to a post earlier, I'm working with

return
, and returning a value from one function to another. I'm a little stuck at the moment.

Below, I'm trying to pass the result of
userName
and
validated
variables into
userCheck
function as the arguments. Something isn't going right, could anyone provide guidance please? Thank you.

var checkInput = function (userName) {
var validated = true; // For use later to decide whether userCheck runs.
var userName = prompt("What is your name?");
var checkType = typeof userName; // Save whether it's a string, number, null, or object.

if (checkType == "object") {
console.log("You clicked cancel.");
validated = false;
} //If cancel is clicked , do this.

else if (userName =="") {
console.log("You didn't enter a name");
validated = false;
} // If they just press enter, do this.

else if (isNaN(userName) == false) {
validated = false;
console.log("That's a number");
} //If it's a number, do this.

else {
return userName;
} //Otherwise, return userName for use elsewhere.
};

var userCheck = function(userEntry, validated) {
var userName = userEntry;
var validated = validated;
var correctMessage = (`Welcome back, ${userEntry}.`);
if (validated == true && userName == "alan" || userName == "rachel") { console.log(correctMessage); }

};

userCheck(checkInput());

Answer Source

You have to return those variables. Try the following.

var checkInput = function(userName) {
    var validated = true; // For use later to decide whether userCheck runs.  
    var userName = prompt("What is your name?");
    var checkType = typeof userName; // Save whether it's a string, number, null, or object.

    if (checkType == "object") {
        console.log("You clicked cancel.");
        validated = false;
    } //If cancel is clicked , do this.
    else if (userName == "") {
        console.log("You didn't enter a name");
        validated = false;
    } // If they just press enter, do this.
    else if (isNaN(userName) == false) {
        validated = false;
        console.log("That's a number");
    } //If it's a number, do this.
    return {
        userName: userName,
        validated: validated
    };
};

var userCheck = function(object) {
    var userName = object.userName;
    var validated = object.validated;
    var correctMessage = (`Welcome back, ${userName}.`);
    if (validated == true && userName == "alan" || userName == "rachel") {
        console.log(correctMessage);
    }

};

userCheck(checkInput());

This will now return an object with the userName and validated. Then in your userCheck function you look at the values within that object. This is because you can only return 1 thing in a function. So we need to get both of those variables into 1 item.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download