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

437 views Asked by At

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.

3

There are 3 answers

0
linstantnoodles On BEST ANSWER

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.

0
aaron-bond On

As long as you declare the variables outside of the function properly (i.e. use "var") you shouldn't have any problems and it helps with making the code easier to read.

0
Sayan On

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.