JavaScript's function definition has a feature, which will first scan the entire function body statement and "upgrade" 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 strict mode, the statement var x = 'Hello, ' + y; does not report an error, because the variable y is declared later. But alert shows Hello, undefined, indicating that the value of the variable y is undefined. This is precisely because the JavaScript engine automatically improves the declaration of variable y, but does not increase the assignment of variable y.
For the above foo() function, the code seen by the JavaScript engine is equivalent to:
function foo() { var y; // declaration of elevating variable y var x = 'Hello, ' + y; alert(x); y = 'Bob';}Due to this weird "characteristic" of JavaScript, when we define variables inside a function, please strictly abide by the rule "to declare all variables first within a function". The most common way is to use a var to declare all variables used internally in the function:
function foo() { var x = 1, // x is initialized to 1 y = x + 1, // y is initialized to 2 z, i; // z and i are undefined // Other statements: for (i=0; i<100; i++) { ... }}The above article on improving the in-depth understanding of js variables is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.