Explain The function Of this Sign Code (Js)

Sorry,I new in JavaScript and have a problem to understand this code

const calculator = {
    displayNumber : '0',
    operator : null,
    firstNumber : null,
    waitingForSecondNumber : false
};

function updateDisplay() {
    document.querySelector("#displayNumber").innerText = calculator.displayNumber;
}

function clearCalculator() {
    calculator.displayNumber = '0';
    calculator.operator = null;
    calculator.firstNumber = null;
    calculator.waitingForSecondNumber = false;
}

function inputDigit(digit) {
    if (calculator.displayNumber === "0"){
        calculator.displayNumber = digit;
    }
    else{
        calculator.displayNumber += digit;
    }
 }

 **const buttons = document.querySelectorAll(".button");**
** for (let button of buttons) {**
**    button.addEventListener('click', function(event) {**

**        const target = event.target;**

**        inputDigit(target.innerText);**
**        updateDisplay()**
**    });**
** }**

@danizarkan You are going to need to be more specific about what part of the code you do not understand.

@RandellDawson yes, I already gave it with this sign (*)

@danizarkan Why don’t you try to explain what you think the code is doing and then we can fill in any gaps or correct what you do not understand?

const buttons = document.querySelectorAll(".button");
// there is a class in your html file called 'button' and we use the DOM to assign its reference to a variable called 'buttons' in this file
//  querySelectorAll will return all class references inside an array [] called 'buttons'
// now we loop  through the buttons array
for (let button of buttons) {
    // for every item in the buttons array we add an event listener
    button.addEventListener('click', function(event) { // this function will run when the button is clicked
        const target = event.target;
        inputDigit(target.innerText);
        updateDisplay()**
    });
}
1 Like

Terimakasih atas penjelasannya,tapi apa fungsi dari “const target = event.target”

  1. mdn: addEventListener
  2. event types
function(event){
        // addEventListener returns an object called event that we use in our function
       // event has a key called 'target that refers to your button item'
        const target = event.target;         
        // we just shorten event.target to 'target' so that its easier to read and type
        inputDigit(target.innerText); // we run target.innerText through the function that was made earlier in yout code
        updateDisplay()
}
1 Like