In JavaScript, local variables are variables declared within the function body or named parameters of the function; local variables have local scope, which means that local variables can only be used within the function in which they are defined. Since local variables are defined within a function, variables with the same name can be used in different functions.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Local variables are variables declared within the function body or named parameters of the function. They have local scope, which means they can only be used within the function in which they are defined. Since local variables are defined within a function, variables with the same name can be used in different functions.
Since var supports variable promotion, the global scope of the var variable is valid for the script code of the entire page; while let and const do not support variable promotion, so the global scope of the let and const variables refers to the script code from The entire area between the beginning of the declaration statement and the end of the script code of the entire page, and the area before the declaration statement is invalid.
Similarly, because var supports variable promotion, but let and const do not support variable promotion, local variables declared using var are valid throughout the function, while local variables declared using let and const are valid from the beginning of the declaration statement to The area between the end of the function is valid. It should be noted that if the local variable and the global variable have the same name, in the function scope, the local variable will overwrite the global variable, that is, the local variable will work in the function body; outside the function body, the global variable will work, and the local variable will work. The variable is invalid, and a syntax error will occur when referencing local variables.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <center> <p>在myfunction()之外没有定义petName。</p> <p id="demo1"></p> <p id="demo2"></p> <script> myfunction(); function myfunction() { var petName = "Sizzer"; // local variabl document.getElementById("demo1").innerHTML = "myfunction()函数内:"+ typeof petName + " " + petName; } document.getElementById("demo2").innerHTML = "myfunction()函数外:"+ typeof petName; </script> </center> </body> </html>
Output:
The above example illustrates the use of local variables. However, statements outside the function cannot reference a variable named petName without causing an error. This is because it has local scope.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of What are local variables in javascript. For more information, please follow other related articles on the PHP Chinese website!