Why are there two ways to define a function in Javascript?

Typically there are two ways to define a function in Javascript. The first is to write:
var myFirstFunction = function()
{
}
For example:
<html>
<script>
var myFirstFunction = function()
{
return 1;
}

document.write(myFirstFunction());
</script>
</html>
and the second is to write:
function mySecondFunction()
{
}

For example:
<html>
<script>
function mySecondFunction()
{
return 2;
}

document.write(mySecondFunction());
</script>
</html>

The question is why bother to learn both? Is there any difference? One of the best places on the Internet to ask coding questions like this is Stack Overflow and it is indeed here where we find an answer thanks to Greg and David Murdoch.

Greg and David explain that "The difference is that [the first type of function] is defined at parse-time for a script block, whereas [the second type of function] is defined at run-time". This means that in the first type the function must be defined before it is called and in the second it is irrelevant whether it is called before or after it is declared, and they provide a very clear example of this, which I will adapt here.
<html>
<script>
//Error
document.write(myFirstFunction());

var myFirstFunction = function()
{
return 1;
}
</script>
<script>
//No error
document.write(mySecondFunction());
function mySecondFunction()
{
return 2;
}
</script>
</html>

If you test this you will find it to be true.

Jason Bunting adds a further detail by explaining that "[the first type of function] is merely a variable that has an anonymous function assigned to it, whereas [the second type of function] is actually a named function", and he explains that we can discover this by calling the .toString() method. So let's try that now by adding the following lines of code to our valid scripts:
document.write("<p>" + myFirstFunction.toString()+"</p>");
document.write("<p>" + mySecondFunction.toString()+ "</p>");

The result you should see in your web browser is:

    function () { return 1; }

    function mySecondFunction () { return 2; }

There are further points made further down the page on Stack Overflow, and for those who seek even more detail and depth I recommend you read on.

Comments