简体   繁体   中英

JavaScript: Is it good practice to use the same name for variables passed to functions?

I imagine this comes up a lot. Let's say I have:

downloadData () {
    var myData = //do something ;
    displayData(myData);
}
displayData (myData) { //<--- is it bad practice to use same variable name myData? 
    //display data
}

Is it good or bad practice (or doesn't really matter) to use the same variable name in the second function displayData() or should I accept myData with some other name, like myDataToDisplay? Both names tell me what's in the var just as effectively.

只要您正确地声明函数外部的变量(即使用“var”),您就不应该遇到任何问题,这有助于使代码更易于阅读。

The variable myData is bounded to the scope of function displayData when displayData is invoked. So it's not like you're risking the possibility of any name collisions.

My general rule of thumb for parameter naming is clarity. So yes, I think it's perfectly fine to use the same name variable names in this case, insofar as they accurately describe the data that is being passed.

As a though experiment, lets suppose we had a hard rule that says "Thou shall not use the same variable names in multiple functions". What if you have multiple functions that call the same data and you're chaining the calls? That won't look pretty.

Its perfectly allright in this case because you are working with two different functions and scope of those variables are different. Though it depends on preference of coder but my suggestion is don't pollute your script by using same name again and again.

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