How can I run in JavaScript a operation, ONLY if the operation result is < 100, as an example.
I tried the following code but the += operation got executed twice, but I only want it to be executed after the if statement.
let progress = 0
function earn(howmuch) {
if (progress += howmuch < 100) {
console.log(progress) // console.logs 1
progress += howmuch
console.log(progress) // console.logs 2
}
}
document.querySelector('.click-area').addEventListener('click', function() {
earn(1)
}
Thanks for help
+=
is an assignment.
In your case the increase happens in the condition check and inside if.
You should change the +=
in the condition to be +
, that way the value won't be changed, just temporary calculated