Why would we want to reassign a new value to a variable?

Why would you need the ability to change the value(?) of a variable after the fact?

changing a variable value is so common, without this ability, programming would be a lot more difficult.

lets say you capture user input in a variable:

var userInput = promt('give me a word: ')

if the user enters multiple words, you can prompt the user again and store the result in the same variable. If you had to store the user input in a different variable each time, that would become tedious if you get wrong input multiple times

there are countless example why re-assign variable is very useful, you will see

11 Likes

let meal = ‘Enchiladas’;
console.log(meal); // Output: Enchiladas
meal = ‘Burrito’;
console.log(meal); // Output: Burrito

From the example in the exercise, the 3rd line does not use the keyword let to reassign a different value. Is this a normal practice?

2 Likes

yes, let, var and const are only used when defining a variable (for scope among other things), once the variable is defined we can just assign it other values.

7 Likes

Hello, I have a question.

Why after changing the value of the variable, it still prints //True

Edit**

I just found out that I forgot to console.log() the variable… Sorry!

But now I have another question!

Every single time a print changeMe will be false after this line?

1 Like

I’m sure this question will be answered, however I’m trying to conceptualize this exercise, I am wondering why would we need to reassign a new value to a variable? Shouldn’t we simply declare a new variable? Wouldn’t it get confusing as the code continues (like re-writing a class in css that gets redefined later on in the style sheet.)

yes, the variable will now hold false until you change it again

1 Like

you can’t compare variable with css.

re-assigning and declaring variables are both concepts you to know for programming.

lets say you want to prompt the user for valid input, it might take the users 5 try to get it right, then i want a single variable (the user input one thing), not 5 variable of which 4 are completely useless.

2 Likes

@acgatorfan There are many reasons to reassign variables. Imagine you have a quiz website.
when a user starts the quiz, their initial score would be zero, as they answer more questions the score increases. So at the end of the quiz their score could be 10. so we need to be able to continuously reassign the variable score to keep track of the score.
This also applies in games, your player health,lives,ammunition etc

12 Likes