Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript boolean compare not working. How to resolve? [duplicate]

Tags:

javascript

<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var status = [true,false,true,false,true,false,true,false,true,false];
var status1 = [true,false,true,false,true,false,true,false,true,false];

document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>

</body>
</html>

https://jsfiddle.net/vdr2r38r/

Why is the behavior different for identical variables with different names?

like image 870
Rahul Yadav Avatar asked Jun 06 '26 11:06

Rahul Yadav


1 Answers

It's because you run your code in global context! var bound variables are bound to the function scope. If you have no function you are in global context, which means in a browser you are on the window object.

This code will log Demo:

<script>
  var foo = "Demo";
  console.log(window.foo);
</script>

Now your code breaks because window.status is reserved.

An easy fix is to surround your code by a function to provide a new context for your variables, which is always good practice.

<script>
    (function() {
        var status = [true,false,true,false,true,false,true,false,true,false];
        var status1 = [true,false,true,false,true,false,true,false,true,false];

        document.getElementById("demo1").innerHTML = status[2];
        document.getElementById("demo2").innerHTML = status1[2];
    })();
</script>
like image 184
Lux Avatar answered Jun 08 '26 00:06

Lux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!