1

I have a Javascript question, that might be obvious, but I just can't seem to find the solution for it, and I don't know how to solve it.

(Also, I'm still pretty new to coding)

So I'm writing a patrol function for squares in my game, and for now I started out with just making the square move one way. Later on I will make it patrol back and forth. That's why I put the move function in the draw function.

I want the move function to be reusable for several squares, but I can't seem to make a general move function work. However, I can make a move function specifically for a certain square, work.

Can anyone tell me why this works:

var square = 16;
var posX = 32;
var posY = 32;

function moveSquare() {
    for (i = 0; i < 10; i++) {
        posX++;
    }
}

function draw() {
    var redSquare = { x: posX, y: posY, w: square, h: square, color: "red" };
    ctx.fillStyle = redSquare.color;
    rect(redSquare.x,redSquare.y,redSquare.w,redSquare.h);

    moveSquare();
}

And this doesn't:

var square = 16;
var posX = 32;
var posY = 32;

function move(pos) {
    for (i = 0; i < 10; i++) {
        pos++;
    }
}

function draw() {
    var redSquare = { x: posX, y: posY, w: square, h: square, color: "red" };
    ctx.fillStyle = redSquare.color;
    rect(redSquare.x,redSquare.y,redSquare.w,redSquare.h);

    move(posX);
}

By the way, I defined the rect function elsewhere, but I figured it wasn't important to include.

Hope you can help

1
  • In move(posX) you're passing posX by value, not by reference. Meaning a copy of posX has 1 added to it ten times and then the function returns, and the original posX remains the same. Commented Dec 17, 2014 at 11:13

1 Answer 1

1

The value passed to the function move is being passed by value, not by reference.

So the pos inside move is private to the move function.

The pos variable will be a copy of posX, so no matter what you do to it in the move function, the global posX will not be affected.

Consider the code:

var x = 5;

function move(x)
{
  x++;
  console.log("In function x is: " + x);
}

console.log("Outside function, before call x is: " + x);

move(x);

console.log("Outside function, after call x is: " + x);

This outputs:

"Outside function, before call x is: 5"
"In function x is: 6"
"Outside function, after call x is: 5"

The function move has it's own private copy x.

Look into pass by reference, pass by value and variable scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.