0

Recursive solution for counting number of zeroes in a number is as below:

    const number = 3004;
   
    const countZeroes = function (num) {
        if (num == 0) {
            return;
        }
    
        if (num % 10 == 0) {
            count += 1;
        }
    
        countZeroes(parseInt(num / 10));
    }
    
    let count = 0;
    countZeroes(3004);
    console.log('the result ', count);

The above solution works fine when we use count as a global variable. But it does not work when count is passed as a reference variable. Please find the solution below:

    const number = 3004;
    
    const countZeroes = function (num, count) {
        if (num == 0) {
            return count;
        }
    
        if (num % 10 == 0) {
            count += 1;
        }
    
        countZeroes(parseInt(num / 10));
    }
    
    let count = 0;
    const result = countZeroes(3004, count);
    console.log('the result ', result);

Does javascript only allows pass by value and not by reference. Please let me know.

JMP
  • 4,417
  • 17
  • 30
  • 41
Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54
  • Objects are passed by reference. – IT goldman Jul 30 '22 at 17:28
  • @ITgoldman All arguments are passed by value. Variables contain references to obejcts. This behavior is unrelated to the function call. You can observe the same behavior without functions, by copying objects. [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – jabaa Jul 30 '22 at 17:29
  • You need to change the last line of the function to `return countZeroes(...)` – Barmar Jul 30 '22 at 17:33
  • Technically yes, but if you pass by value a reference to an object (which object variables are) then effectively you pass the object by reference. – IT goldman Jul 30 '22 at 17:33
  • You're missing the second argument in the recursive call. It should be `return countZeroes(parseInt(num / 10), count);` – Barmar Jul 30 '22 at 17:33
  • @ITgoldman The difference is, that you don't need a function call to observe this behavior. Your simplification doesn't describe the actual behavior and leads to confusion. `let a = {}; let b = a; b.a = 2`. No function call involved. `a` and `b` are modified. – jabaa Jul 30 '22 at 17:34
  • The problems have nothing to do with pass by value or reference. – Barmar Jul 30 '22 at 17:34

0 Answers0