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
Question about Javascript-foundations > variables > scope
Why is it that this doesn't work when you take out the "inner ()" and the "sayHello();" that are at the end?
var world = "World!";
function sayHello() { var hello = "Hello ";
function inner () {
var extra = " There is more!"
console.log(hello + world + extra);
}
inner();
}
sayHello();
2 Answers
Ian Lunn
4,558 PointsA function is code that you are saving to use later and often more than once. If your script just contained a function, like this:
function sayHello() {
console.log('Hello!');
}
Nothing would happen because code inside a function isn't run until the function is referenced.
When you later reference the function, like this:
sayHello();
You are then telling the browser to run the code within the sayHello() function.
Thank you very much Ian!
Alan