Javascript Why Am I Not Getting Name Already Exist Error
Solution 1:
let
is block scoped, which means having multiple declarations in multiple blocks is okay. Each time you call sumSalaries()
the sum
will be reset to zero. It doesn't need to remember previous calls because it will return the sum if finds for this call which, as the recursion unwinds, will be added to the parent who called the recursive function.
It can be instructive to watch the recursion with strategically placed, console.log()
calls or by using a debugger. For example you can watch the sum add up with:
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)
console.log("starting new object")
let sum = 0;
for (let subdep of Object.values(department)) {
let subsum = sumSalaries(subdep)
console.log("subsum = ", subsum)
sum = sum + subsum;
}
console.log("current sum:", sum)
return sum;
}
}
console.log(sumSalaries(company));// 6700
Solution 2:
Each time you call a function, it creates a new space (usually called 'scope' or 'stack-frame') to hold all the variables declared inside of it.
Variable-already-declared errors only show up when you declare the same variable twice in the same space
Because the 'sum' variables created inside the first call to sumSalaries and the second (recursive) call are in different spaces, there's not going to be an error.
Solution 3:
In javascript, a function is, in essence, a scope.
Recursive calls of the same function will also be independent scopes. The variable sum
declared in the previous recursive function call will not be the same as the one declared on the next.
You'll only get the
Identifier has already been declared
if you declare the variable twice in the same scope.
Post a Comment for "Javascript Why Am I Not Getting Name Already Exist Error"