This article analyzes the importance of var in javascript. Share it for your reference. The specific analysis is as follows:
The var function of javascript is to declare variables.
Generally speaking, you won’t make mistakes without writing, but in some cases, you will have different results if you don’t write. Let’s take a look at the following example:
<div id="a"></div> <script type="text/javascript"> a = 1; alert(a); </script>
The above example will not be problematic when executing FF Chrome, and it can output 1. But what about running in IE? Error: "object doesn't support this property or method".
Because the reference of the DOM element can be obtained directly through id in IE, an error will be reported if a=1, because a at this time is the DOM element of id="a".
If you remove the <div id="a"></div>, there will be no problem. In order to avoid this conflict, it is recommended to declare variables with var.
I hope this article will be helpful to everyone's JavaScript programming.