English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
A feature of JavaScript function definition is that it scans the statements in the entire function body first, and 'promotes' all declared variables to the top of the function:
'use strict'; function foo() { var x = 'Hello, ' + y; alert(x); var y = 'Bob'; } foo();
Although it is in strict mode, the statement var x = 'Hello, ' + y; does not cause an error because the variable y is declared later. However, the alert displays 'Hello, undefined', indicating that the value of variable y is undefined. This is because the JavaScript engine automatically promotes the declaration of variable y, but does not promote the assignment of variable y.
For the above foo() function, the code that the JavaScript engine sees is equivalent to:
function foo() { var y; // Promote the declaration of variable y var x = 'Hello, ' + y; alert(x); y = 'Bob'; }
Due to this strange 'feature' of JavaScript, when defining variables inside a function, please strictly follow the rule of 'declare all variables at the beginning of the function'. The most common practice is to use a var statement to declare all variables used within the function:
function foo() { var x = 1, // x is initialized to1 y = x + 1, // y is initialized to2 z, i; // z and i are undefined // Other statements: for (i=0; i<100; i++) { ... } }
This article on the in-depth understanding of JavaScript variable hoisting is all the editor shares with everyone. I hope it can provide a reference for everyone and hope everyone will support the Shouting Tutorial.