I am learning JavaScript.
I was practicing applying closures but I got stuck and am not able to find the issue with my code.
function change_greeting() {
let on_or_off = 1;
return function button() {
if (on_or_off) {
document.getElementById("demo") = "Hello";
} else {
document.getElementById("demo") = "Goodbye";
}
}
}
const click = change_greeting();
<button onclick=click()>Click Me</button>
<p id="demo"></p>
I tried a similar example without mixing it up with events, at that time it succeeded. I am not sure as to what change I must bring to my code.
3
Answers
You should rewrite this
to this (add changing the value to make toggle work):
on_or_off
1,0,1,0,etc… use the Remainder operator%
after an increment:on_or_off = ++on_or_off % 2
or simply usingXOR
assignmenton_or_off ^= 1;
on
* inline attribute handlers. Use addEventListener() insteadAnd here’s the example using XOR assignment:
For completeness, instead of using integers
1,0,1,0...
you could instead use a boolean variable and switch it usingisOn = !isOn
and, as you can see in the latest example, there’s no need to store the closure in a
click
variable. If not used elsewhere you can simply call it within the click handler.addEventListener("click", change_greeting());
Additionally (as seen in this examples), you can replace the 5 lines of
if/else
with a readable, well known and loved Ternary (conditional) operatorstatement ? truthy : falsy
Basing the toggle logic on a
boolean
value and making more out of the advantage of dealing with a created closure, the OP’s example code could be streamlined to something much more readable as …