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
1494 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:

  • hahah1
  • hahah2
  • hahah3
  • hahah4
  • Copy after login
    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);
                }
            }
    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('p').getElementsByTagName('li');
            for(let i = 0; i < li.length; i++) {            
                li[i].onclick =function(event) {
                    console.log('li : '+i+'  '+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!