Analysis of the difference between Const, VAR and let in JavaScript

Source: Internet
Author: User

Let is a bug that fixes the scope of Var and becomes more useful. Let is the better var. The function of Var is then applied, and let is the block level (the content enclosed in braces)
Const declared variables can only be assigned at the time of declaration, not arbitrarily modified, this is the biggest feature.

A variable declared with Var, whose scope is within the function where the statement is located, and there is a variable elevation phenomenon;
Use a let declaration of a variable whose scope is within the code block where the statement resides, and there is no variable elevation;
A constant is declared with const, and the value of the constant cannot be modified in the code that appears later.

variables defined by 1.const cannot be modified and must be initialized .

12345 const b = 2;//正确// const b;//错误,必须初始化 console.log(‘函数外const定义b:‘ + b);//有输出值// b = 5;// console.log(‘函数外修改const定义b:‘ + b);//无法输出

2.var defined variables can be modified, if not initialized will output undefined, will not error.

123456789 var a = 1; //var a;//will not error console.log ( + A ); //can output a=1 function change () { a = 4; console.log ( + A ); //can output a=4 } change (); console.log ( "function call after Var definition a for function internal modified value: ' + a); //can output a=4

3.let is a block-level scope, and after the function is defined with let, there is no effect on the outside of the function.

12345678 let c = 3;console.log(‘函数外let定义c:‘ + c);//输出c=3function change(){let c = 6;console.log(‘函数内let定义c:‘ + c);//输出c=6} change();console.log(‘函数调用后let定义c不受函数内部定义影响:‘ + c);//输出c=3

Analysis of the Const, VAR, and let differences in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.