0

please see the code below

myduplicates = iterationProc(2, [1, 2, 3, 1]);
console.log(myduplicates);

function iterationProc(curItem, currArr) {
  let duplicates = -1; // line A
  currArr.forEach((item, index) => {
    if (curItem === item) {
      duplicates += 1; // line B
    }
  });
  return duplicates; // line C
}

I am having some difficulty understanding scoping concepts. I have commented three lines A,B, and C. At line B the variable duplicates is getting the value from line A due to lexical scoping in javascript. I understand this. But in my understanding since line C is an outer block as compared to line B so variable duplicates at line C should not get value from line B but retain the value from line A. However at line C the variable does get the value from variable at line B. What am i missing ?

silverkid
  • 9,291
  • 22
  • 66
  • 92
  • 1
    Line C is in the same scope as Line A. – Barmar Jul 23 '20 at 23:33
  • 1
    There's only one variable. Its scope is the entire `iterationProc` function, including any nested functions. – Barmar Jul 23 '20 at 23:35
  • You are basically mutating `A` value – dave Jul 23 '20 at 23:35
  • 1
    You seem to be assuming that the nested function gets a copy of the variable, so its changes shouldn't persist when it's done. That's not how it works. – Barmar Jul 23 '20 at 23:36
  • @dave does the word mutating imply that something unusual is happening ? – silverkid Jul 23 '20 at 23:41
  • @barmar I can understand what you are saying partially, because now i cant seem to understand what is lexical scoping then ? can you show me some code where lexical scoping works, that is outer block does not get the value from inner block – silverkid Jul 23 '20 at 23:45
  • 1
    Put `let duplicates = 0;` in the inner function. Then the inner function has its own variable, so it doesn't update the variable from the outer function. – Barmar Jul 23 '20 at 23:46
  • 1
    Put `console.log(item, index)` in the outer function. It will get an error because those variables are local to the inner function. – Barmar Jul 23 '20 at 23:47
  • @barmar, Now i think i get it thanks. – silverkid Jul 23 '20 at 23:48
  • @silverkid, nothing unusual. It means you are modifying variable's original value. – dave Jul 24 '20 at 07:22

0 Answers0