1) In the following code, what is the reasoning behind making gameOfLive
a variable and not just function gameOfLife()
?
2) What is go
var gameOfLife = function() { }
is a function expression, whereas
function gameOfLife() { }
is a function declaration.
To quote Juriy ‘kangax’ Zaytsev about Function expressions vs. Function declarations:
There’s a subtle difference in behavior of declarations and expressions.
First of all, function declarations are parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated foremost any other expressions contained in a scope. […]
Another important trait of function declarations is that declaring them conditionally is non-standardized and varies across different environments. You should never rely on functions being declared conditionally and use function expressions instead.
In this case, as Joel Coehoorn mentions in a comment, gameOfLife
is defined conditionally, so it's needed to use a function expression.
A general use case for these conditionally defined functions is to enhance JavaScript functionality in browsers that don't have native support for newer functions (not available in previous ECMAScript/JavaScript versions). You don't want to do this using function declarations, as those will overwrite the native functionality anyway, which is most likely not what you want (considering speed, etc.). A short example of this:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item, from) {
/* implement Array.indexOf functionality,
but only if there's no native support */
}
}
One major drawback of function expressions is that you in fact assign an anonymous function to a variable. This can make debugging harder, as the function name is usually not known when script execution halts (e.g., on a breakpoint you set). Some JavaScript debuggers, like Firebug, try to give the name of the variable the function was assigned to, but as the debugger has to guess this by parsing the script contents on-the-fly, this can be too difficult (which results in a (?)()
being shown, instead of a function name) or even be wrong.
(for examples, read on on the page, though its contents are not entirely suitable for beginners)