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 trialTony Brackins
28,766 Pointsdeclaring a variable in a function without using "var"
I was wondering why JS lets you declare a variable in a function without using "var", then assign it to the Global Scope.
2 Answers
Zach Allan
19,452 PointsJim warns at the end of the video that defining a variable without the 'var' keyword is a bad practice and can cause bugs in your code so I would stay away from doing that. He was just explaining what JS does by default if you assign a variable without the 'var' keyword.
Botttom line: ALWAYS assign variables with 'var' keyword. At least from what I know so far...
Michael Jurgensen
8,341 PointsHi Tony,
I am not sure why javascript allows you to create variables without the keyword var. However not using var can have some negative side effects. When you create a variable normally with the keyword var javascript sets a DontDelete flag to the variable. However without the keyword var the variable can actually be deleted!