On Stack Overflow I frequently see questions with code in the following style:
function funcName(parameter) {
let variable = parameter;
// rest of function uses variable rather than parameter
}
Is this just some cargo-cult practice that some programming teachers pass on, or are there coding style guidelines that actually recommend it?
The only justification I can think of for this would be in languages that pass parameters by reference, if the function needs to reassign the variable without affecting the caller's variable. Is this a legacy of instructors who grew up learning Fortran, which passes all parameters by reference? Most other languages with by-reference parameters require them to be declared explictly, as in C++'s type ¶meter
declaration, and in these cases it's usually desirable to modify the caller's variable.
This style of coding for variables that are reassigned is discussed in Is there a reason to not modify values of parameters passed by value?. But I also see this in functions that only read the variable. For instance, this question has a function like this:
function say(messages = [{text: ' ', speed: 90, pause: false, colour: ['RED//BLUE']}]){
let alphabets = [];
let textLines = messages
console.log(textLines.length)
textLines.forEach((line, i) => {
if (i < textLines.length - 1) line.text += " ";
// more code
});
});
It could just as easily be written with textLines
as the parameter name.