+ 2

What is the benefit to use function parameters?

Hi. I just reised that I don't practicing the usage of parameters. So instead of func(int x){} I like to use function(){ int x; }. For some reason I understand and see better the flow of data and scopes with the second way.

5th May 2018, 6:15 AM
Varadi Nikica {🧙}
Varadi Nikica {🧙} - avatar
2 Antworten
+ 2
Hi Varadi it's normal for beginners to use Global variables in their functions. The problem is that globals are prone to making your code buggy and hard to maintain, as they can be changed by any piece of code that you are writing. In a large program it's easy to forget which bit of code is updating what variable. by using function parameters, you start on your journey into clean pure functions, where the function only returns an answer based in its inputs. You can then progress onto not having your functions touch anything outside of itself, so debugging is easy. You pass in parameters and check the output. After this you learn to pass in objects and arrays, and then move into passing functions and returning functions. This allows you to compose your code cleanly and makes it very readable and easy to maintain and refactor.
5th May 2018, 6:44 AM
Mike Choy
Mike Choy - avatar
+ 5
function foo(x) { var y = Math.pow(x, 2); return y; } function bar() { return foo(5); } The above example explains the use. If you had x as a scope variable within foo(), you won't be able to access it inside bar(). Here we are accessing x through function arguments.
5th May 2018, 6:31 AM
Dev
Dev - avatar