When is it allowed to reassign a variable?

Hi, i’ve been having trouble with this concept from the beginning. I’ve seen scripts in which people will use a variable and then reassign it. When are you allowed to do that, and when is it not allowed?

void MoveDoors(float newLeftXtarget, float newRightXtarget) //when called we will lerp only the x position of each inner door that will follow the closing outer doors
	{
		float newX = Mathf.Lerp (leftInnerDoor.position.x, newLeftXtarget, doorSpeed * Time.deltaTime);    //using mathF.lerp instead of vector3.lerp because only the X position is being lerped...
		leftInnerDoor.position = new Vector3(newX,leftInnerDoor.position.y, leftInnerDoor.position.y); // setting positon of door with new offset x position coordinate
	
		newX = Mathf.Lerp (rightInnerDoor.position.x, newRightXtarget, doorSpeed * Time.deltaTime);
		rightInnerDoor.position = new Vector3(newX,rightInnerDoor.position.y, rightInnerDoor.position.z); // ????? reassigning var
	}

In this code for instance the variable newX is reassigned to be used again for a Mathf.Lerp. Can someone help me in the understanding of reassigning a variable. Its somewhat fustrating because i’ve never been able to understand the idea behind it.

This may be a cleared example of reassinging

int i = 0
while(i < 5)
{
    DoSomething();
    i++;
}
for(i = 0; i < 5; i++)
{
    DoSomething();
}

It’s ok to reassign a variable to safe memory space, only if the use of the reassigned variable is not going to be needed in the future. In the example above is not needed and thats why it can be reassigned.

In your example, the newX variable wont be used again, so its legit to reassing it again.

In some cases, reassigning shouldn’t be done to keep the code clear. But here the name of the variable fits what it represent.

Anyway, as far as I know, visual studio reassigned variables when it noticed they were not going to be used again. So in this next example, the inner code will be swiched to give the same output as the code I put before. No idea if mono do this.

int i = 0
while(i < 5)
{
    DoSomething();
    i++;
}
for(int j = 0; j < 5; j++)
{
    DoSomething();
}

This shouldn’t be done. Because playerVictories is getting a completely different concept on it, and the variable name may create confussion at the time of reading the code.

int playerVictories = GetPlayerVictories();
ShowOnScreen(playerVictories);
playerVictories = GetPlayerHP();
ShowOnScreen(playerVictories);