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 trialLi Xia
4,671 Pointsvar syntax
To clarify, was myNumber = 42; inside myFunc a var?
If so, why isn't the keyword var needed as a prefix?
2 Answers
Adam Sackfield
Courses Plus Student 19,663 PointsYes it was a variable. You don't need to use the var keyword inside a function, however if you do this then that variable will be made available globally ie outside the function. See these examples
var red = "This is red";
console.log(red); // This would output "This is red" globally
function myFunction () {
var blue = "This is blue";
red = "This is now pink";
green "This is green";
console.log(blue); // This would output "This is blue"
console.log(red); // This would output "This is now pink" globally
console.log(green); // This would output "This is green" globally
} // Function ends
console.log(blue); // This would output "ReferenceError: blue is not defined" as it is only available locally inside the function as the var keyword was used
console.log(red); // This would output "This is now pink" globally as the call to the "red" variable has changed the global variable red
console.log(green); // This would output "This is green" globally
Li Xia
4,671 PointsGot it, thank you so much for your help Adam and Dino!
Dino Paškvan
Courses Plus Student 44,108 PointsDino Paškvan
Courses Plus Student 44,108 PointsYou don't need to use the var keyword inside a function
This is not necessarily true. Yes, the engine will create a global variable upon reaching the global scope, but in strict mode, not using the var keyword will throw a ReferenceError. And strict mode is (and should be) used more and more.
Adam Sackfield
Courses Plus Student 19,663 PointsAdam Sackfield
Courses Plus Student 19,663 PointsOk thanks for the tip Dino Paškvan