Search code examples
javascriptjavascript-objects

Why the value of my function does not update with the value of my object


I'm doing an exercise about rover in Mars I have the object rover that has direction as property and default value 'N' (north), he needs first turn before to go forward, it means that if the rover wants to move to the left, it’s first move must be a turn, next move will then be a step forward. when I run the function to moveLeft(rover) The results are as expected. He turns perfect!! BUT the value of property direction is never updated, and I need this value update to the next step... I'm going to paste a part of my code. Thank you!

  direction: 'E',
  x: 0,
  y: 0,
  path: { x: 0, y: 0 },
  travelLog: []
}
var move = rover.direction

function moveLeft (who) {
  console.log(`Rover is facing ${move}`)
  switch (move) {
    case 'N':
      move = 'W'
      console.log(`Rover is facing now ${move}`)
      break;
    case 'W':
      move = 'S'
      console.log(`Rover is facing now ${move}`)
      break;
    case 'S':
      move = 'E'
      console.log(`Rover is facing now ${move}`)
      break;
    case 'E':
      move = 'N'
      console.log(`Rover is facing now ${move}`)
      break;
    default:
      console.log(`Please insert the correct directions`)
  }
  console.log('turnLeft was called!')
}

This is my output

Rover is facing E
Rover is facing now N
turnLeft was called!

console.log(rover)
{direction: "E", x: 0, y: 0, path: {…}, travelLog: Array(0)}

console.log(move)
W

console.log(rover.direction)
E

I expect the output of rover.direction to be the same of move

Solution

  • This line:

    var move = rover.direction
    

    is copying the value of rover.direction into the variable named move, it does not create a reference to rover.direction. When you do something like this:

    move = 'W'
    

    it only updates the move variable, it does not update rover.direction.

    To fix this, you can either add a line like:

    rover.direction = move;
    

    after your switch statement, or you can get rid of the move variable and work directly on rover.direction.

    Also, a couple notes/suggestions:

    1. You are defining move outside of the moveLeft function. That creates another global variable in addition to the global rover variable. In general, you want to limit the number of global variables to be as few as possible.

    2. Your moveLeft function takes a who parameter that you are not currently using within the function. From your description, it looks like you intend to pass the rover variable in that parameter. In that case, you probably want to remove all references to move and just work with who.direction within your function.