alan2here
alan2here

Reputation: 3317

Javascript passing numbers by reference issue with simple recursive function

I've built this simple recursive function.

The recursion is easily visible as it should draw a tree like nested pattern of boxes. The boxes are also shifted downwards slightly each iteration to make it clearer where there are overlapping lines.

    ___________
1. |           |
   |           |
   |           |
   |           |
   |           |
   |___________|

    ___________
2. |___________|
   |     |     |
   |     |     |
   |     |     |
   |     |     |
   |_____|_____|
   |_____|_____|

    __ __ __ __
3. |___________|
   |_____|_____|
   |  |  |  |  |
   |  |  |  |  |
   |  |  |  |  |
   |__|__|__|__|
   |__|__|__|__|
   |__|__|__|__|

http://codepen.io/alan2here/pen/reFwo

var canvas = document.getElementById('canvas').getContext('2d');

box(50, 50, 150, 150);

function box(x, y, width, height) {
  // draw the box
    line(x, y, x + width, y);
    line(x, y, x, y + height);
    line(x, y + height, x + width, y + height);
    line(x + width, y, x + width, y + height);

  // continue with a tree like nested pattern of sub-boxes inside this one.
    if (width > 100) {
      width2 = width * 0.5;
      box(x, y + 5, width2, height);
      box(x + width2, y + 5, width2, height);
    }
}

function line(x, y, x2, y2) {
  canvas.beginPath();
  canvas.moveTo(x, y);
  canvas.lineTo(x2, y2);
  canvas.closePath();
  canvas.stroke();
}

However, this abruptly stops working at iteration 3, as can be seen if width > 100 is changed to width > 50.

    __ __ __ __
3. |_____      |
   |__|__|     |
   |  |  |     |
   |  |  |     |
   |  |  |     |
   |__|__|_____|
   |__|__|
   |__|__|

It seems as if values may be getting passed by reference where they shouldn't be, however I thought numbers in JS passed by copying the value, and what's more I'm creating most of the passed values from scratch, for example ..., x + width, ... and width2 = width * 0.5.

Why is the program not working.


Thanks Benni for the slight correction.

Upvotes: 0

Views: 59

Answers (2)

Guffa
Guffa

Reputation: 700412

Variables are always passed by value in Javascript. It doesn't even support passing parameter by reference.

The problem is that you are using a global variable:

width2 = width * 0.5;

When you make the first recursive call it will change the value of the global variable, so the second recursive call will use the value from the last iteration instead.

Declare the variable in the function so that it is local:

var width2 = width * 0.5;

Upvotes: 2

Benvorth
Benvorth

Reputation: 7722

First guess: change your code to

 if (width > 100) {
  var width2 = width * 0.5;
  box(x, y + 5, width2, height);
  box(x + width2, y + 5, width2 , height);
}

Upvotes: 1

Related Questions