Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFrances Angulo
5,311 Pointsvar str vs. str
In the example, the teacher defined str as "Hello Playground" and below defined str as "Hello World". How does the application know what value to interpret when referencing just 'str' and why wold you redefine a variable in this way?
3 Answers
Stone Preston
42,016 Pointswhen you declare a variable/constant
var str = "some string"
that variable is basically a container that can store a value. right now str has a value of "some string".
However I can reassign str a different value by referencing it by its name, str
var str = "some string"
//reasssign the value of str
str = "some other string"
now str no longer has a value of "some string", it has a new value of "some other string"
How does the application know what value to interpret when referencing just 'str' and why wold you redefine a variable in this way?
it doesnt have to choose a value to interpret, the variable holds one and only one value. The application just says "give me the value stored in str." Since str has one value, whatever is currently stored, there is no confusion.
Once you reassign the variable a new value the old value is gone. You redefine variables because the value needs to change. For example, suppose you had a text field and a label that displays whatever is typed into the text field. any time a user finished typing something in you need to change the labels value.
Frances Angulo
5,311 PointsOK ! So it sounds like you'd reassign values when you want to essentially recycle the name. The 'program' will read top down so the variable value is correct UNTIL you decide it changes. Correct?
Stone Preston
42,016 PointsOK ! So it sounds like you'd reassign values when you want to essentially recycle the name
pretty much. variables are a way to associate a logical name with a value. Suppose you had a variable called firstName that stored someones name. Well maybe later on they decide they wanted to change their firstName to a nickname so you would change the value of that variable, whilst still keeping the same logical name for that variable
I know it seems hard to understand the applications of variables and etc when you are writing such small programs, but once you start creating apps it will be easier to see the importance
wang xi
Courses Plus Student 285 Pointsreally helpful! thanks!