Undefined Variable

I'm working on building a calculator app with little knowledge of JS (jumping into an example to force myself to learn).

What I'm trying to do is take an input and add to a variable 'total'. Currently, the variable 'total' is undefined. Based on button click, it gets defined by whichever number is pressed. However, when outputting, it pre-fixes with 'undefined' despite being defined prior to output (see attachment)

How could I go about fixing this?

let expression = document.querySelector(".expression");
let btns = document.querySelectorAll(".btn");
let total;

for (let i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function (){
        if (btns[i].classList.contains("number")) {
            console.log("number");
            total = total + btns[i].id;
            expression.innerHTML = total;
        } else if (btns[i].classList.contains("operator")) {
            console.log("operator lol");
        }
    });
}
image.png
Was this page helpful?