Книга: Functional Programming in JavaScript
Назад: The function constructor
Дальше: Summary

Unpredictable behavior

So the difference is that function declarations are hoisted while function expressions are not. This can cause unexpected things to happen. Consider the following:

function foo() {   return 'hi'; } console.log(foo()); function foo() {   return 'hello'; }

What's actually printed to the console is . This is due to the fact that the second definition of the function is hoisted to the top, making it the definition that is actually used by the JavaScript interpreter.

While at first this may not seem like a critical difference, in functional programming this can cause mayhem. Consider the following code snippet:

if (true) {   function foo(){console.log('one')}; } else {   function foo(){console.log('two')}; } foo();

When the function is called, is printed to the console, not !

Finally, there is a way to combine both function expressions and declarations. It works as follows:

var foo = function bar(){ console.log('hi'); }; foo(); // 'hi' bar(); // Error: bar is not defined

It makes very little sense to use this method because the name used in the declaration (the function in the preceding example) is not available outside the function and causes confusion. It would only be appropriate for recursion, for example:

var foo = function factorial(n) {   if (n == 0) {     return 1;   } else {     return n * factorial(n-1);   } }; foo(5);

Назад: The function constructor
Дальше: Summary

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)