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
Kirk Rohani
Full Stack JavaScript Techdegree Student 2,312 PointsNeed parenthesis () when calling functions sometimes and not other times?
Why is it that when we call functions we usually need to put parenthesis (i.e. var randomQuote = getRandomQuote()) however in other cases we don't.
For example in calling window.setInterval(printQuote, 30000) I noticed that if I put parenthesis after printQuote() I received some wierd error somewhere else in my script file however without them the code works just fine.
2 Answers
Alexander Davison
65,469 PointsIf you use parentheses, you are calling the function.
If you don't use parentheses, you are just referring to that function and not really calling the function.
The cool thing about functions is that you can have functions as arguments:
function callFunc(func) {
func();
}
function hello() {
document.write("<h1>Hello!</h1>");
}
With those functions in mind we can call the callFunc function with the hello function as an argument.
Note that you shouldn't use parentheses since we are not calling the function (in the callFunc function we are) but referring to that specific function.
callFunc(hello);
And when we want to call functions we use the parentheses:
hello();
I hope you understand more :)
Good luck! ~alex
Kirk Rohani
Full Stack JavaScript Techdegree Student 2,312 PointsThanks Alex! Yes, that was a great explanation to my question and the concept.
I really appreciate the quick response as well.
Thanks! Kirk
Alexander Davison
65,469 PointsNo problem :)