Home Is it normal to use in the function some variable with the same name as it function?
Reply: 1

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

Yellowfun
1#
Yellowfun Published in 2018-02-10 16:48:09Z

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?

Carcigenicate
2#
Carcigenicate Reply to 2018-02-10 16:59:25Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342555 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO