search
HomeWeb Front-endFront-end Q&AWhat does javascript variable promotion mean?

What does javascript variable promotion mean?

Feb 07, 2022 pm 02:00 PM
javascriptvariable promotion

In JavaScript, variable promotion means that within the scope of a variable, no matter where the variable is declared, it will be promoted to the top of the scope, but the order of variable initialization remains unchanged. The actual implementation of variable hoisting is that JavaScript variable and function declarations are placed into memory during the compilation phase.

What does javascript variable promotion mean?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

What is variable promotion?

Variable hoisting (Hoisting) is people’s understanding of how JavaScript execution context works, and it is not an official change.

Literally understood, variable promotion means that the declarations of variables and functions will be moved to the front of the scope in the physical layer. Although this understanding is not accurate, the effect is the same.

In layman's terms, variable promotion means that within the scope of a variable, no matter where the variable is declared, it will be promoted to the top of the scope, but the order of variable initialization remains unchanged.

The actual implementation of variable promotion is that the declaration of JavaScript variables and functions will be placed into memory during the compilation phase. This means that users can use a function or variable before it is formally declared.

To understand the implementation of variable promotion, we must first clarify the following two points:

  • javascript code is not executed line by line.

  • javascript execution is divided into 2 steps:

    • Compilation (lexical interpretation/pre-interpretation)

    • Execution

Variable promotion helps understanding

console.log(a);
var a = 'ghostwu';

For the above code example, the first line of code, you may think that an error is reported, Because the a variable is not defined before a is output, but the correct result is undefined.. According to the above explanation of the js execution code, combined with the actual code, when we encounter var a = "ghostwu" to define a variable, js actually regards this sentence as two stages, var a occurs in the compilation stage , a = 'ghostwu' occurs in the execution phase. Then var a will be promoted to the front of the current scope, a = 'ghostwu' stays in place waiting for the execution phase, so look at the following case:

 a = 'ghostwu';
 var a;
 console.log( a );
 
 //上面这段代码经过编译之后,变成下面这样

 var a;  //被提升到当前作用域的最前面
 a = 'ghostwu'; //留在原地,等待执行
 console.log( a ); //输出ghostwu
 
 
 
  console.log( a ); 
   var a = 'ghostwu';

   //上面这段代码,经过编译之后,变成下面这样
   
   var a;
  console.log( a );//输出undefined,而不会报错
   a = 'ghostwu';

Function declaration promotion

Before explaining function declaration promotion, let’s first understand the two common ways of defining functions

         //函数声明, 形如:
         function show(){
             console.log( '函数声明方式' );
         }
 
         //函数表达式, 形如:
         var show = function(){
             console.log( '表达式方式' );
         }

Because function expression The declaration of expressions and functions will have different interpretation effects during the compilation phase, so the declaration of the function will be promoted. For an example, see the following code:

         show();
         function show(){
             console.log( a );
             var a = 'ghostwu';
         }


//函数声明会被提升,所以上面的代码经过编译之后,就变成下面这样

    function show(){    //函数声明被提升到 当前作用域的最前面
    var a;    
     //var声明被提升到当前作用域的最前面, 注意,他不会提升到函数的外面, 因为当前的作用域是在函数中
    console.log( a );
    a = 'ghostwu';
   }
   show();//输出undefined

But the function expression will not be promoted, see below Example:

show(); //报错,show is not a function
var show = function(){
 console.log( 'ghostwu' );
}
//对于上面这段表达式代码,经过编译之后:
var show;
show();  //执行之后就是 undefined(), 所以在表达式定义之前,调用函数报错了
show = function(){
  console.log( 'ghostwu' );  
}

But look at the following case:

show(); //你好
var show;
function show(){
console.log( '你好' );
}
show = function(){
   console.log( 'hello' );
}

Why does the above code output "Hello"? Because when a function declaration or variable declaration with the same name appears, the function declaration will is promoted first, variable declarations are ignored. So after compilation, it becomes:

function show(){
   console.log( '你好' );
}
show(); //你好
show = function(){
  console.log( 'hello' );
}
show();//如果这里在调用一次,就是hello, 因为show函数体在执行阶段被重新赋值了

But if there is a function declaration with the same name, the latter one will overwrite the previous one, as follows:

show(); //how are you
var show;
function show(){
console.log( 'hello' );
}    
show = function(){
console.log( '你好' );
}
function show(){
console.log( 'how are you!' );
}  

//上面的代码经过编译之后,变成如下形式:
function show(){
   console.log( 'how are you!' );
}
show(); //how are you
show = function(){
 console.log( '你好' );
}
show(); //如果在这里再执行一次,结果:你好

Note:

  • #Variable promotion only promotes the declaration of the variable, and does not promote the assignment.

  • Because there is such a thing as variable promotion, in order to avoid the bad effects caused by variable promotion, we'd better use let when defining variables. instead of var.

【Related recommendations: javascript learning tutorial

The above is the detailed content of What does javascript variable promotion mean?. For more information, please follow other related articles on the PHP Chinese website!

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
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),