Yellowfun
Yellowfun

Reputation: 558

Is it normal to use in the function some variable with the same name as it function?

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;
};
This code works fine without any warnings. But I'm curious can it lead to any trouble?

Upvotes: 0

Views: 73

Answers (1)

Carcigenicate
Carcigenicate

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

Related Questions