- Function names must be verbs.
- The name of each function should accurately reflect what the function does.
- A function should only do what its name explicitly implies, and shouldn't do anything else.
- Each function should only perform one action.
- Use helper functions inside functions.
-
It is better not to make function code
longer than
10
-15
lines. - It is better to break long functions into a number of auxiliary ones.
-
Use common prefixes in function names:
show
,get
,set
,calc
,create
,change
,check
. - Move duplicate code into functions.
Write down the flaws in the following code and fix them:
function sum(arr) {
let res = 0;
for (let elem of arr) {
res += elem;
}
return res / arr.length;
}
Write down the flaws in the following code and fix them:
function func(arr1, arr2) {
let res1 = 0;
for (let elem of arr) {
res1 += elem;
}
let res2 = 0;
for (let elem of arr) {
res2 += elem;
}
return res1 / res2;
}
Write down the flaws in the following code and fix them:
function getSum(arr) {
let res = 0;
for (let elem of arr) {
res *= elem;
}
return res;
}