Reassigning variables

I understand that there are 3 types of variables, var, let, and const. As I understand, var and let can be reassigned. I don’t get why would we actually need to reassign variables. Can anybody give me an example of how you can do it in a real situation? I am a very beginner and this is so confusing!
Thank you.

Hi there and welcome to the forums!

There are many situations where you might want to reassign a variables value, but lets pick a single example. Imagine you are building a simple game where the user does something and either gets a point or doesn’t. In that case as the user continues to play you want to keep track of their points. The best way to do this would be to have a variable that keeps their score, so for example.

// Initialise the game
let userScore = 0;
let userGuess = "";
let word = "";
// Set the first word
word = "avocado";
// user guesses a wrong word, nothing happens
userGuess = "apple";
// user guesses the right word, score increases
userGuess = "avocado";
userScore = userScore + 1;
// sets new word and user guesses it right again
word = "pear";
userGuess = "pear";
userScore = userScore + 1;

This is of course not representative of a real program and just for examples sake. However here we can see that whenever the user guesses right, userScore gets reassigned to the value of userScore + 1. Therefore at the end of this code, we should see that userScore has a value of 2, even though it started off having a value of 0.

The main time variables will be reassigned is when you want to track some information throughout the program, where that info could change based on the user inputs.

1 Like