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 trial

JavaScript JavaScript Basics (Retired) Storing and Tracking Information with Variables Introducing Variables

Kelvin Ribeiro
Kelvin Ribeiro
2,814 Points

What's the point to create a var for a string, if you have to change that var to display a different string?

alert("Hello"); alert("My name is Kelvin");

-------------------------------------¦¦-------------------------------------

var message = "hello"; alert(message); message = "My name is Kelvin"; alert(message);

-------------------------------------¦¦------------------------------------- Because both codes at the top does the same thing, is there any specific for reason why giving a string a variable is better when it makes your code longer?

6 Answers

andren
andren
28,558 Points

A lot of the code shown off in these videos are there to teach you some concept more so than to show you the most efficient code imaginable. This video is mainly about teaching the basics of variables.

Assigning a string to a variable if you only use it in one place is often pointless, as you state. The main point of assigning a string to a variable are in instances where the string is used in multiple places in your code, or in cases where you need to use that string in a later part of your code.

Kelvin Ribeiro
Kelvin Ribeiro
2,814 Points

Makes sense, thank you for your time to explain.

I'm sure there are plenty of reasons. Let's say your variable was called "Bottles", and you intended to run a program that ran the 99 Bottles of beer song. Well, when it came down to bottle 1, you would need to utilize the singular word bottle. In this case, you can create a conditional that would state if bottleCount is equal to 1, your variable bottles would now = "bottle".

Max Botez
Max Botez
5,146 Points

sorry but didn't get it

So the original question is could we have duplicated code doing the same?

Gary Reid
Gary Reid
1,860 Points

@Max, I think the original question was asking why set the var value, as it increases the amount of code. Andren provided what Im guessing is the most reasonable assumption, in that we've only done that to teach the concept of variables.

I think the instructor is just giving examples on how variables changes its value . Variables often change it value depending what you're programming.