2

I was trying to comprehend the behaviour of Javascript and recursive programming.

Npw, I am sort of beginner so I need to understand why do I get already have been declared error and when I don’t get already have been declared error

Consider this code, I was trying to understand how this will execute..

 let company = { // the same object, compressed for brevity
      sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 600 }],
      development: {
        sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
        internals: [{name: 'Jack', salary: 1300}]
      }
    };
    
    // The function to do the job
    function sumSalaries(department) {
      if (Array.isArray(department)) {
        return department.reduce((prev, current) => prev + current.salary, 0);
      } else { // case (2)
        let sum = 0;
        for (let subdep of Object.values(department)) {
          sum = sum + sumSalaries(subdep); 
        }
        return sum;
      }
    }
    
   console.log(sumSalaries(company));// 6700

Breaking the execution of the above code (correct if I am understanding this wrong)

  1. We are passing company as an argument to sumSalaries
  2. Inside sumSalaries, we are checking if it is an array or not

Intitally it is not an array since company is an object above.

  1. We will pass it else condition with declaration of let sum = 0
  2. object.values will give us two arrays (based from company)
  3. In the first iteration of let subdep of Object.values(department, we will get
    [{…}, {…}] inside which we have following object {name: "John", salary: 1000}
  4. Here our sum = 0, we will add our sum with return of what we passing to sumSalaries(subdep);
  5. Now since we are passing the array, it will go to following function

    if (Array.isArray(department)) {
    return department.reduce((prev, current) => prev + current.salary, 0);
    }

  6. Her in our previous we are passing 0 and adding it with current.salary.

  7. Since we are using reduce, hence it will first add 0 + 1000 and then it will add 1000 + 600
  8. This will return us 1600 and hence our sum would be 0 + 1600
  9. Now our loop will do second iteration, which gives us an object consisting of two arrays …
  10. Since it is an object, It won’t pass into if (Array.isArray(department)) { and go to else instead

Problem + Question
While, I was completing the thirteen point, I realised that our second declaration have let sum = 0

So, Two things

  1. Since we have let sum = 0, shouldn’t there be an error stating that let sum already exsist

  2. Either way, we are doing sum = 0, does that mean our previous value (1600) in the sum array is gone (or in other words reset to zero?