简体   繁体   中英

Not writing “var” before new variable in JavaScript

I am just learning JavaScript, and I don't understand why the following code doesn't produce an error:

myTest = 5;
function addFifteen(num) {
    return num+15;
}
document.write(addFifteen(myTest));

Why do I not need "var" before "myTest"? If it runs without "var", what is the purpose of writing that?

When you do not specify a var before the variable, it is still valid javascript. This is why it does not produce an error. However, as a best practice, you should avoid this, because variables thus declared get tagged to the global scope window .

Having too many variables / functions thus declared is said to "pollute" your global scope and isn't considered good programming practice.

There is a more thorough explanation about this on MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM