Hi.
I’m doing some basic Javascript tutorials on the W3 schools site.
Here’s my example within the TryIt editor on this page:
http://www.w3schools.com/JS/tryit.asp?filename=tryjs_function_return2
<html>
<head>
<script type="text/javascript">
function myFunction()
{
return ("Hello world!");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(myFunction())
</script>
</body>
</html>
returns “Hello World”.
But, If I take away the () next to the function
<script type="text/javascript">
document.write(myFunction)
</script>
What is returned in the browser is:
function myFunction() { return "Hello world!"; }
Why is this? And again, what are the rules for this? When can you get away without the parenthesis, and is it appropriate to use? Is there ever a time when you must not include them? When must you use them?
I ask b/c in Essential Javascript at Lynda.com, the author frequently calls a function without the parenthesis and that has caused me severe confusion.
Thanks, bowie101
In your own example there were two separate results.
To call a function, the parentheses must be used. A function name used without parentheses forms a function reference; it does not call the function but specifies a function to be called.
document.write(myFunction) calls your function’s toString method, causing its content to be written.
Thanks for answering! Can you explain just a bit further? Every point you made, unfortunately, I didn’t understand.
What do you mean there were 2 results in my own example? You mean apart from the good result and the bad result I gave? No, I don’t think you mean that. …so…
Function reference? to further specify? Can you give an example? That might illustrate the point. Never heard of a function reference. .
I think both results I got were strings brought about by the same method, no?
document.write(myFunction)
passes the function itself into the document.write so the actual function code gets printed.
document.write(myFunction())
runs the function and returns the result to the document.write so that the value returned is what gets printed.
With that type of code you probably want the second rather than the first. There are situations though where you want the first such as when you assign a function to an event handler. You want the function to run when the event handler is called so you want the event handler to have the function assigned.
window.onload = myFunction
What you wouldn’t want is to have the function run straight away with the result assigned to the event handler
window.onload = myFunction()
would run the function now rather than when the onload event is called so unless the result returned is another function it wouldn’t do anything useful.
If it helps to aid understanding, myFunction just by itself is a reference to the function. The function itself doesn’t run.
With myFunction() the parenthesis are invoking the function, causing it to return a result.
ok. that is starting to make sense. thanks.