Tips for creating functions in JavaScript

  1. Function names must be verbs.
  2. The name of each function should accurately reflect what the function does.
  3. A function should only do what its name explicitly implies, and shouldn't do anything else.
  4. Each function should only perform one action.
  5. Use helper functions inside functions.
  6. It is better not to make function code longer than 10-15 lines.
  7. It is better to break long functions into a number of auxiliary ones.
  8. Use common prefixes in function names: show, get, set, calc, create, change, check.
  9. Move duplicate code into functions.
Задание 1

Write down the flaws in the following code and fix them:

javascriptfunction sum(arr) {
  let res = 0;
  
  for (let elem of arr) {
    res += elem;
  }
  
  return res / arr.length;
}
Задание 2

Write down the flaws in the following code and fix them:

javascriptfunction 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;
}
Задание 3

Write down the flaws in the following code and fix them:

javascriptfunction getSum(arr) {
  let res = 0;
  
  for (let elem of arr) {
    res *= elem;
  }
  
  return res;
}