0

I have two functions at the top of my code. Below in a while (i<1) loop, I call one of the functions above. This works the first time, but the second time the function is called it displays an error:

TypeError: undefined is not a function

Below is the code:

var i = 0;
var newBalance = 0;
var deposit = function(amountIn)
{
    newBalance = (newBalance + amountIn).toFixed(2);
};
var withdrawl = function(amountOut)
{
    newBalance = (newBalance - amountOut).toFixed(2);
};
var choice = prompt("Would you like to access your account?").toLowerCase();
if (choice === "yes"){
    while (i<1){

        var inOrOut = prompt("Are you making a deposit or a withdrawl?").toLowerCase();
        var strAmount = prompt("How much money are you trasfering?");
        var amount = parseFloat(strAmount);

        if (inOrOut === "deposit")
        {
            deposit(amount);
        }
        else if (inOrOut === "withdrawl")
        {
            withdrawl(amount);
        }
        else
        {
            console.log("You did not enter a valid number");
        }

        console.log("Your new balance is $" + newBalance);
        var choiceTwo = prompt("Would you like to make another transaction?").toLowerCase();
        if (choiceTwo === "no")
        {
            i = i + 1;
        }
    }
}
1
  • I sincerely hope this is not a real financial transaction.... Commented Oct 3, 2014 at 13:58

1 Answer 1

1

Initially, you set newBalance to a number. Calling either of your functions, however, will set newBalance to a string. (toFixed returns a string, not a number.) After that, newBalance + amountIn will also be a string (and be completely different from what you want — the + will denote string concatenation rather than addition), so it will not have a toFixed method. So you get the error you see.

To fix this, modify your functions so that they do not convert newBalance to a string. You should use toFixed only when you are displaying the balance:

console.log("Your new balance is $" + newBalance.toFixed(2));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.