Reputation: 558
Is it normal to use in the function some variable with the same name as it function?
const sum = function(arr) {
let sum = 0;
for(let i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
};
Upvotes: 0
Views: 73
Reputation: 45741
It's generally bad practice to "shadow" variable names. It can cause confusion about what's being referenced if you aren't careful.
In this example, there isn't a major downside. Consider though if later you decided to make the function recursive. If you tried to call sum
from within itself, you'd get an error that sum
isn't a function, because it's finding the inner variable sum
, not the function. That's not a major issue, but it's a good idea to write code that is less likely to break in weird ways in the future. You never know what changes you might make later on.
Upvotes: 3