Home > Web Front-end > JS Tutorial > body text

The difference between variables defined by const, var and let in JavaScript

php是最好的语言
Release: 2018-08-09 11:40:55
Original
1569 people have browsed it

1. Const declares a constant (The value pointed to by const is unchanged, so it must be initialized, otherwise an error will be reported, while the values ​​pointed to by var and let are variable and can be reassigned. You can Not initialized)

## Correct way of writing: const h = 'nnnn';

Incorrect way of writing: const h;

2 , var and let declare variables. The difference between the two is the scope

(1), var

Example 1:

function fun(){
        	var a=5;
        	console.log(a);
 }
Copy after login

Note : If placed inside a function, it is a local variable. Variable a can only be used within the function fun(), otherwise an error will be reported

Example 2:

<p id=&#39;p&#39;>
		<li>hahah1</li>
		<li>hahah2</li>
		<li>hahah3</li>
		<li>hahah4</li>
</p>
Copy after login
var li =document.getElementById(&#39;p&#39;).getElementsByTagName(&#39;li&#39;);
        for(var i = 0; i < li.length; i++) {            
            li[i].onclick =function(event) {
                console.log(&#39;li : &#39;+i+&#39;  &#39;+this.innerHTML);
            }
        }
Copy after login

Note: Example 2, it is a global variable, so each click corresponds to the same i

The difference between variables defined by const, var and let in JavaScript

(2), let declares a variable, statement or expression whose scope is limited to the block level

For example:

var li =document.getElementById(&#39;p&#39;).getElementsByTagName(&#39;li&#39;);
        for(let i = 0; i < li.length; i++) {            
            li[i].onclick =function(event) {
                console.log(&#39;li : &#39;+i+&#39;  &#39;+this.innerHTML);
            }
        }
Copy after login

Note: The i in this place can only be in the for loop statement block Use

The difference between variables defined by const, var and let in JavaScript

Related recommendations:


var, let, const in js Usage difference

Difference between const, var and let in js

The above is the detailed content of The difference between variables defined by const, var and let in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!