Declaring Variables Without "var" Keyword: The Perils of Implicit Globals
At w3schools, it is stated that variables declared without the "var" keyword become global. While this may seem like a convenient way to declare global variables, it can lead to a significant problem known as "The Horror of Implicit Globals."
Consider the following example:
function foo() { variable1 = 5; varaible2 = 6; return variable1 variable2; }
You might expect this function to return 11; however, it returns NaN due to a typo on the "varaible2 = 6;" line. Worse still, this typo inadvertently creates a global variable with the misspelled name "varaible2."
The problem arises when this global variable is inadvertently modified outside the scope of the "foo" function, leading to unexpected behavior and potential security vulnerabilities.
Therefore, it is strongly recommended to always declare variables using the "var" keyword, even for global variables. By explicitly declaring variables, you ensure that they are properly scoped and avoid the pitfalls of implicit globals.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3