strange behaviour of variable named "status" in javascript
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>
The word status
is a reserved keyword, so you need to rename it like status3
or something else. See snippet below. You can also see a list of reserved words by visiting this link: http://www.w3schools.com/js/js_reserved.asp
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var status3 = [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 = status3[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>
</body>
</html>
I hope this will help you.
change variable name 'status' , it is a Windows Reserved Word. In HTML you must avoid using the name of HTML and Windows objects and properties
ES6 / ES2015 solution
Use let
or const
when declaring your global variables. They do not get defined on the window object. Therefore, clashes with window.status
or window.name
and other properties of the global object can be avoided.
Demonstration below:
let
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let status = [true,false,true,false,true,false,true,false,true,false];
let 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>
const
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const status = [true,false,true,false,true,false,true,false,true,false];
const 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>
See also What's the difference between using "let" and "var"?