nww04
nww04

Reputation: 1857

Checking for javascript booleans weird behavior

Hello guys I am actually doing a simple javascript which checks for boolean. I know this has been asked many times. I am fairly new to javascript and this is pretty much all about basic isn't?

<script>
var boolValue = true;
function f1()
{
     if(boolValue == true)
          alert("This is true!");
     else
          alert("This is false!");
}
</script>

The thing is this script never works. boolValue is true even though boolValue is set to false. I don't know if I missed something here, but this is pretty trivial to other language I come across. You have a variable declared outside a function on the same scope. I expect that boolValue can be accessible inside f1()? I've also done this with ===.

so here is what I am actually doing I am playing around tutorials on W3C basic intro on JavaScript. I played around and I wanted to do a toggling effect on the button which changes the message to and from.

so here what I did:

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p>JavaScript can change the content of an HTML element:</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo">This is a demonstration.</p>

<script>

var status = true;

function myFunction() 
{   
if(status == true)
{
    document.getElementById("demo").innerHTML = "Hello World!";
    status = false;
}   
else
{
    document.getElementById("demo").innerHTML = "This is a demonstration.";
    status = true;
}
}

</script>

</body>
</html>

Also making var to global doesn't change it either. How do you check for boolean values in javascript? Especially, changing variables declared outside a function and change that variable on within that function? However, if I change booleans to signals like integer, 0 or 1. It works. Want I wanted is similar behavior to boolean.

I am using Opera. I don't have other browser to test this. Thank you!

Upvotes: 0

Views: 694

Answers (1)

JJJ
JJJ

Reputation: 33163

The problem is with the variable name. When used globally, status refers to a member of the window object. window.status was used by a feature that's now disabled in most browsers so you can't set it anymore. See https://developer.mozilla.org/en-US/docs/Web/API/Window.status for more information.

The solution then is to either use another name for the variable (like flag or something) or wrap the whole thing in a function so that it becomes a local variable.

Upvotes: 4

Related Questions