0

I expect to be able to use 'validBet' in a new function. The validBet is the basically the last value of the array 'betButtonsArr'. So the last clicked button will be the bet, not any of the previous. Now I need to be able to use the validBet to determine the bet placed, to calculate loss/winnings in a new function.

The problem is that I get a validBet is undefined error.

I am only using VanillaJS since I want to learn JS first before moving onto libraries.

    // starter cash will be 100.
    var cashTotal = 100; //Cash currently holding.
    var showTotal = document.querySelector("#amount").innerHTML = cashTotal;
    var bet = [5, 10, 50, 100]; //Bets you can do.

    var numGenerated;
    function updateDisplay() {
      document.querySelector('#generated_number').innerHTML = "".split.call(numGenerated, "").join("");
    }

    function highLow(){
        var storeNum = Math.floor(Math.random() * 11) + 0;
        numGenerated = storeNum;
    }


    function choiceLow(){
        highLow();
        updateDisplay();
        console.log(numGenerated);
        if (numGenerated < 5){
            // run function to add winnings
        }
        else {
            // run function to subtract bet amount.
            return;
        }
    }

    function choiceHigh(){
        highLow();
        updateDisplay();
        console.log(numGenerated);
        if (numGenerated == 5 || numGenerated > 5){
            // run function to add winnings.
        }
        else {
            // run function to subtract bet amount.
            return;
        }

    }

    var betAmount = [];
    function placeBet(){
        var betBtn_nodelist = document.querySelectorAll('.bet_amount > button');
        var betButtonsArr = Array.prototype.slice.call(betBtn_nodelist);
        //
        for (var i = 0; i < betButtonsArr.length; i++) {
            betButtonsArr[i].onclick = function(){ // when clicked, push value of clicked button to betAmount array for grabbing the placed bet.
                betAmount.push(this.value);
                console.log(betAmount);

                var validBet = betAmount[betAmount.length - 1]; // when multiple bet amounts are clicked, take the last amount chosen, make that the final and valid bet amount.
                console.log(validBet) //This is the real bet amount, as explained one line above.
                console.log(cashTotal)
            }
        }
    }
    placeBet();

    function addWinningsAmount(){

    }


    function subtractBetAmount(){

    }



    var lower = document.querySelector("#lower");
    var higher = document.querySelector("#higher");

    lower.addEventListener('click', choiceLow);
    higher.addEventListener('click', choiceHigh);

HTML code:

     <!DOCTYPE html>
    <html lang="en" dir="ltr">
        <head>
            <meta charset="utf-8">
            <title>Betting Project</title>
            <link rel="stylesheet" href="betting.css">
        </head>
        <body>
            <div class="cash_total"><p>Your balance is: <span id="amount"></span>.</p></div>
            <h1 style="text-align: center;">BET NOW</h1>
            <div class="bet_amount">
                <button class="five" value="5">5</button>
                <button class="ten" value="10">10</button>
                <button class="fifty" value="50">50</button>
                <button class="hundred" value="100">100</button>
            </div>
            <div id="generated_number"></div>
            <div class="buttonHolder" style="text-align: center;">
                <button id="lower">LOWER</button>
                <button id="higher">HIGHER</button>
            </div>
            <script src="betting.js"></script>
        </body>
    </html>

I expect to use this and grab the value of the bet. Instead of that, I get the ReferenceError: validBet is not defined. I'm guessing this is a scoping problem, but I have no idea how to best sort this out.

function addWinningsAmount(){
    console.log(validBet)
}
Daniel
  • 60
  • 6
  • `var validBet` makes the variable local to the anonymous function you assign as click event handler here. – misorude Jan 17 '19 at 10:40
  • When do you need to call `addWinningsAmount`? If that is supposed to happen when the button is clicked, then you can simply call it from within your event handler, and pass the variable you can access perfectly fine in there as a parameter to this function … – misorude Jan 17 '19 at 10:43
  • I'll need to add that to both functions: choiceHigh and choiceLow, same goes for subtractbetAmount. It'll be added into the if/else statements. -- I have also tried declaring the validBet variable before the function itself, but it still comes up undefined. Not sure what the right way is. Still kind of new to JS. – Daniel Jan 17 '19 at 10:49
  • It is a scoping related. If you want to see the results immediately, you can try initiate 'validBet' at the top, under 'bet'. – Mo A Jan 17 '19 at 10:49
  • If I declare it at the top, right under the placeBet function, I still can't access it in addWinningsAmount() – Daniel Jan 17 '19 at 10:52
  • Still haven't got this sorted. – Daniel Jan 17 '19 at 11:13
  • I meant declare it under ' var bet = [5, 10, 50, 100];'. Then this ' var validBet = betAmount[betAmount.length' becomes ' validBet = betAmount[betAmount.length' – Mo A Jan 17 '19 at 11:37

1 Answers1

1

when declaring global objects in javascript, you need to declare it at the top. Any variable declared inside a function is limited to that function only.

or else, if the variable still needs to be declared inside the function but with global scope, use window declaration. For eg. window.validBet = betAmount[betAmount.length - 1];. Make sure the function declaring the variable is called before the function accessing the variable.

do not use 'var' while declaring global variables.

M M
  • 655
  • 1
  • 7
  • 16
  • I'm guessing declaring a global variable should be declared using 'let'? Unless it's a const? – Daniel Jan 17 '19 at 12:29
  • no. _let_ creates block scope variables. _var_ creates function/global scope variables. _window_ creates global scope variables. [This](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav) explains the concept quite well. – M M Jan 17 '19 at 14:29