incrementing and decrementing works as expected but I need the number to display ‘0’ instead of ‘undefined’ if it becomes zero or less.
Currently, When it becomes zero, it goes one step more and returns undefined.
I need it to stay zero when it gets to zero.
let counter = 0;
const add = (function() {
return function() {
counter += 1;
return counter;
}
})();
const sub = (function() {
return function() {
if (counter >= 1) {
counter -= 1;
return counter;
}
}
})();
function addFunction() {
document.getElementById("demo").innerHTML = add();
}
function subFunction() {
document.getElementById("demo").innerHTML = sub();
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.buttons {
background: crimson;
margin: 10px;
width: 130px;
color: white;
text-align: center;
padding: 4px;
display: flex;
justify-content: space-around;
border-radius: 5px;
}
button {
width: 45px;
height: 20px;
margin: 5px;
}
p {
margin: 5px;
}
<!DOCTYPE html>
<html>
<body>
<div class="buttons">
<button type="button" onclick="addFunction()">+</button>
<button type="button" onclick="subFunction()">-</button>
<p id="demo">0</p>
</div>
</body>
</html>
3
Answers
You don’t return anything when your condition fails. Just return your counter behind your if, so it will always return something.
You just have to
return 0
in yoursub()
function as the fallback condition (else condition)Working code below
You could clean the code a bit by using the function directly without returning a function without cause.