Can I declare the same variable twice in different for loops in JavaScript? [duplicate]

偶尔善良 提交于 2019-11-29 09:04:38

Any use of var foo in a function will scope foo to that function. It doesn't matter where in the function this takes place as var declarations are hoisted.

Additional uses of var foo in the same function are syntactically legal but will have no effect as the variable is already scoped to that function.

Since it has no effect, there is a school of thought that recommends against it (and in favour of a single var function at the very top of a function to perform all the scoping) to avoid implying that there is significance to it (to maintainers who are not entirely comfortable with this feature of JavaScript). JSLint will alert you to this usage.

No you shouldn't. JavaScript has function scope, not block scope!

I'm saying shouldn't because it might suggest that the variable is local to the loop/block when it isn't.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!