Home  >  Article  >  Web Front-end  >  Analysis of the Importance of Var in JavaScript_Basic Knowledge

Analysis of the Importance of Var in JavaScript_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 16:14:352068browse

This article analyzes the importance of var in JavaScript with examples. Share it with everyone for your reference. The specific analysis is as follows:

The function of var in JavaScript is to declare variables.

Under normal circumstances, there will be no mistakes if you don’t write, but in some cases, if you don’t write, there will be different results. 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 run without problems in FF Chrome and 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 the id under IE, an error will be reported if a=1, because a at this time is a DOM element with id="a".

If you remove the sentence ef063bec93c7d2fd366870dafe54b63b16b28748ea4df4d9c2150843fecfba68, there will be no problem. In order to avoid this kind of conflict, it is recommended that variables must be declared with var.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn