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)
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); }
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='p'> <li>hahah1</li> <li>hahah2</li> <li>hahah3</li> <li>hahah4</li> </p>
var li =document.getElementById('p').getElementsByTagName('li'); for(var i = 0; i < li.length; i++) { li[i].onclick =function(event) { console.log('li : '+i+' '+this.innerHTML); } }
Note: Example 2, it is a global variable, so each click corresponds to the same i
(2), let declares a variable, statement or expression whose scope is limited to the block level
For example:var li =document.getElementById('p').getElementsByTagName('li'); for(let i = 0; i < li.length; i++) { li[i].onclick =function(event) { console.log('li : '+i+' '+this.innerHTML); } }
Note: The i in this place can only be in the for loop statement block Use
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!