Robby_rob
Robby_rob

Reputation: 309

Console.log returns wrong answer

I'm new to JS, it's my first logical programming language. For some reason no matter what my income and loanAmount is the else console.log is returned. What can't I get the "Approved" message to show?

function LoanApp(personName, income, loanAmount){
    this.personName = personName;
    this.income = income;
    this.loanAmount = loanAmount;

    var bankBranch = "New York";
    var approvalStatus = "invalid";

    this.submit = function (income, loanAmount){
        if (income / loanAmount >= 2) {
            approvalStatus = "Approved";
            console.log("Congrats you're approved for " + this.loanAmount + ".")
        } else {
            approvalStatus = "On Review";
            console.log("Your application needs further review.")
        };
    };
};

var tony = new LoanApp("Tony"5000,1000);
tony.submit();  //returns else console.log but should be "Congrats"

Upvotes: 1

Views: 63

Answers (2)

Larry Lane
Larry Lane

Reputation: 2191

All you have to do is append the keyword this to the variables in your if then statement that determines if the value is >= 2. This will give the function access to the variables, otherwise it can't access them because they are out of the scope of the function.

Javascript: jsfiddle example - http://jsfiddle.net/larryjoelane/zrkdyq9c/6/

function LoanApp(personName, income, loanAmount){
    this.personName = personName;
    this.income = income;
    this.loanAmount = loanAmount;

    var bankBranch = "New York";
    var approvalStatus = "invalid";

    this.submit = function (income, loanAmount){
        if ((this.income / this.loanAmount) >= 2) {  //<-----change that fixes code



            approvalStatus = "Approved";
            console.log("Congrats you're approved for " + this.loanAmount + ".")
        } else {


            approvalStatus = "On Review";
            console.log("Your application needs further review.")
        };
    };
};

var tony = new LoanApp("Tony",5000,1000);
tony.submit();  //returns else console.log but should be "Congrats"

Upvotes: 0

tckmn
tckmn

Reputation: 59273

Your submit function is defined as function (income, loanAmount). Since you don't pass anything to the function, both are set to undefined, and undefined / undefined >= 2 evaluates to false.

All you have to do to fix this is:

  1. Remove the parameters from the function declaration.

  2. Replace all occurrences of income with this.income (and same with loanAmount) in the function, so it knows what scope to look for them in.

Upvotes: 3

Related Questions