简体   繁体   中英

Why var variable in javascript become global when used in for loop?

I have been told the variable defined by var in javascript will be local.

For example:

function myFunc(){var v=100; return v;}

if you access the v outside the function you will hit

Uncaught ReferenceError: v is not defined

But then I found when using in for loop, the variable defined by var become global. For example

for(var i=0;i<10;i++){/*do nothing*/}

After the for loop you can still access the variable i. Why it becomes global? What is the difference when using in function and for loop?

In JavaScript, var is scoped only to the next function scope, ignoring all other kinds of blocks (if, for, while, etc.)

You can use let instead to solve this, which is scoped to blocks instead. Also look into const , which behaves the same as let , but can't be reassigned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

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