I'am kind of new to javascript and today I was working on a function that basically toggles a value and displays it as alert but I stumbled across a weird behavior of JavaScript relating to true/false and 0/1.
The following code , when user clicks on toggle anchor link, it doesn't seem to toggle the value and the alert always gives "true" (which i thought should happen):
document.body.innerHTML = '<a href="#" id="toggle"> toggle </a>'+ document.body.innerHTML;
function f() {
this.status = true;
var btn = document.getElementById("toggle")
btn.addEventListener("click", () => {
if (this.status == true) {
alert(this.status)
this.status = false;
} else {
alert(this.status)
this.status = true;
}
}, false)
}
f()
But if I use 0 and 1 instead of true/false the code works for some reason.
document.body.innerHTML = '<a href="#" id="toggle"> toggle </a>' +document.body.innerHTML;
function f() {
this.status = 1;
var btn = document.getElementById("toggle")
btn.addEventListener("click",()=>{
if(this.status==1){
alert(this.status)
this.status = 0;
}else{
alert(this.status)
this.status = 1;
}
},false)
}
f()
I have no idea what's going on here, Is this because of this
pointer i am using in the function or something?.