Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange behaviour of variable named "status" in javascript

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 639
Rahul Yadav Avatar asked May 30 '16 09:05

Rahul Yadav


People also ask

What is the unique name for the JavaScript variables?

Variable Names in JavaScript Variable names are case-sensitive in JavaScript. So, the variable names msg , MSG , Msg , mSg are considered separate variables. Variable names can contain letters, digits, or the symbols $ and _. A variable name cannot start with a digit 0-9.

What are the three types of variables in JavaScript?

In JavaScript, there are three different variable types: var , let , and const . Each of these variables have several rules around how they should be used, and have different characteristics. In this tutorial, we are going to explore the basics of variables in JavaScript.

What are the two types of variables in JavaScript?

JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.


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 122
Lux Avatar answered Oct 20 '22 00:10

Lux