can someone explain to me !lockButton in this jquery

This is partial code from a simple calculator exercise:

From my understanding the ! reverses the boolean value, so since lockButtons was set to false, is it now true in the first if statement? But later below in the if check =, we set lockButtons to true so it stops any numbers from being inputted, it's probably simple but i can't wrap my head around it.

 var firstNumber = "";
      var secondNumber = "";
      var operator = "";
      var result = 0;
      var hasNumber = false;
      var firstNumberComplete = false;
      var lockButtons = false;

      // Check if any button is clicked...
      $(document).on("click", "button", function() {

        // Checks if it's a number and that its not the end of the calculation ("!lockButtons")
        if ($(this).hasClass("number") && !lockButtons) {

          // We'll then set our "hasNumber" variable to true to indicate that we can proceed in selecting an operator.
          hasNumber = true;

          // If we haven't received an operator yet...
          if (firstNumberComplete === false) {

            // Then grab the number of the value clicked and build a string with it
            firstNumber += $(this).attr("value");

            // Print the number to the firstPage
            console.log(firstNumber);

            // Print it to the div
            $("#first-number").html(firstNumber);
          }

          // If we have received an operator already...
          else {

            // Grab the number of the value clicked and build a string with it
            secondNumber += $(this).attr("value");

            // Print the number to the firstPage
            console.log(secondNumber);

            // Print it to the div
            $("#second-number").html(secondNumber);
          }
        }

        // Checks if its an operator (but not "=")
        if ($(this).hasClass("operator") && hasNumber && !lockButtons) {
          firstNumberComplete = true;

          // Set the visual to show the operator's symbol
          $("#operator").html("<h1>" + $(this).text() + "</h1>");
          operator = $(this).attr("value");
        }

        // Checks if the equal button has been pressed. If so...
        if ($(this).hasClass("equal")) {

          // Lock the keyboard from being clicked
          lockButtons = true;

Answers 1

  • var lockButtons = false;
    

    This statement creates a boolean variable which which can have a value of true or false. So you can use it directly in if

    if(lockbutton)
    

    Since lockbutton is set to false the statements inside if will not be executed.

    if ($(this).hasClass("number") && !lockButtons)
    

    This statement should be clear to you. if both the conditions are true then only the statements inside if will be executed.

    Also I think it's pretty clear why a statement has been put at a particular place by the comments above almost all of them.


Related Articles