Example of JavaScript variable escalation:
Let's take a look at two pieces of code.
function getSum() { var sum = a + b; var a = 1; var b = 2; return sum; } getSum();
function getSum() { var sum = a + b; a = 1; b = 2; return sum; } getSum();
You can take a look at the similarities and differences between the two codes and determine the results obtained after the execution.
The NaN obtained when executing the first code is because the variable declaration in the function is promoted. Before executing "sum = a + B", a is implemented first, b's definition, but since there is no value assignment (the value assignment will not be upgraded), the values of a and B are all undefined and eventually become sum = undefined + undefined, and then get the result of NaN.
When executing the second part of the code, the returned result is "ReferenceError: a is not defined". An exception is thrown that a is undefined. Here, a and B in the function are regarded as global variables because they are not defined by var. Therefore, the declarations of a and B are not upgraded in the function; the "sum = a + B" operation is executed at the beginning of the function. When this sentence is executed, the definitions and values of a and B will be found step by step along the scope, because no corresponding definition is found here (no global scope is available), a undefined exception is thrown (in fact, B will throw an undefined exception ).
Change the second code to the following:
a = b = 3; function getSum() { var sum = a + b; a = 1; b = 2; return sum; } getSum();
Run the code again. In this case, the values of a and B are found in the global scope.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.