Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics Storing and Tracking Information with Variables Introducing Variables

JAAFAR CHRAIBI
JAAFAR CHRAIBI
1,775 Points

What happens if i add a new "var" each time i want to change the value of the variable ?

?

4 Answers

Steven Parker
Steven Parker
212,245 Points

A variable should only be declared once. If you use the keyword "var" on the same variable a second time, it is not proper programming. But duplicate variable declarations using "var" will not trigger an error, so you can "get away with it". :see_no_evil:

However, if you use the newer "let" keyword instead, it will cause an error.

Dinesh P
Dinesh P
415 Points

It won't result in an error. But using var every time is just an extra work 😄

Using "var" for declaring variable again and again will not result in error, but note it will increase the size of javascript file.

Example:(Tested on windows 10):

  1. var superhero = "Spider-Man"; superhero = "Venom"; The above content resulted in file-size of 51 bytes.

  2. var superhero = "Spider-Man"; var superhero = "Venom"; The above content resulted in file-size of 55 bytes.

Extra 4 bytes will not cause much of issue, but if you adapt this practice and write large js files, then there will be a significant difference in file-size.

In programing, it is not recommended to declare the same variable every time using 'var'. However, it does not give any error if you use 'var' again for the same variable but it's not a good practice.