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 Foundations Variables Shadowing

var syntax

To clarify, was myNumber = 42; inside myFunc a var?

If so, why isn't the keyword var needed as a prefix?

2 Answers

Yes 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

You 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.

Ok thanks for the tip Dino Paškvan

Got it, thank you so much for your help Adam and Dino!