javascriptswitch-statement

Keep total from resetting on basic banking app


I'm working on a basic banking app for a beginning JS class.

Expected:

Actual:

Is there a way to adjust this code to keep a running balance?

function bankingApp() {
  let currentBalance = 0;
  let userPrompt = prompt(
    "bank menu: w = withdrawal | d = deposit | b = balance |  q = quit"
  );

  switch (userPrompt) {
    case "w":
      function withdrawFunds() {
        let withdrawAmount = parseFloat(prompt("Withdraw amount: "));
        currentBalance = currentBalance - withdrawAmount;
        console.log(
          "Withdraw: " + withdrawAmount + "New balance: " + currentBalance
        );
      }
      withdrawFunds();
      break;

    case "d":
      function depositFunds() {
        let depositAmount = parseFloat(prompt("Deposit amount:"));
        console.log(
          "Deposit: " + depositAmount + "New balance: " + currentBalance
        );
      }
      depositFunds();
      break;

    case "b":
      function checkBalance() {
        let balance = currentBalance;
        console.log(balance);
      }
      checkBalance();
      break;

    case "q":
      function quitProgram() {
        let quit = "Quit the program.";
        console.log(quit);
      }
      quitProgram();
      break;

    default:
      console.log("That menu is not available.");
  }
}

Solution

  • You are calling your function on an event happening(button click). Now the first statement in your function is setting the balance to 0. There is nothing keeping track of it.

    Simply move the statement out, so the variable persists.

    let currentBalance = 0;
    
    function bankingApp() {
    
      let userPrompt = prompt(
        "bank menu: w = withdrawal | d = deposit | b = balance |  q = quit"
      );
    
      switch (userPrompt) {
        case "w":
          function withdrawFunds() {
            let withdrawAmount = parseFloat(prompt("Withdraw amount: "));
            currentBalance = currentBalance - withdrawAmount;
            console.log(
              "Withdraw: " + withdrawAmount + "New balance: " + currentBalance
            );
          }
          withdrawFunds();
          break;
    
        case "d":
          function depositFunds() {
            let depositAmount = parseFloat(prompt("Deposit amount:"));
            console.log(
              "Deposit: " + depositAmount + "New balance: " + currentBalance
            );
          }
          depositFunds();
          break;
    
        case "b":
          function checkBalance() {
            let balance = currentBalance;
            console.log(balance);
          }
          checkBalance();
          break;
    
        case "q":
          function quitProgram() {
            let quit = "Quit the program.";
            console.log(quit);
          }
          quitProgram();
          break;
    
        default:
          console.log("That menu is not available.");
      }
    }