The distinction goes a bit deeper than your two examples. MDN provides a good explanation, but I'll give a quick overview:
There are function declarations:
function add(a, b) { return a+b; }
Function declarations must be named.
There are named function expressions:
const plus = function add(a, b) { return a+b; };
And there are anonymous function expressions:
const plus = function(a, b) { return a + b };
As far as I understand, the way you write functions is largely a style choice.
The main differences are:
add(1,3); //works plus(1,3); // ReferenceError: can't access lexical declaration `plus' before initialization function add(a, b) { return a+b; } const plus = function namedadd(a, b) { return a+b; };
const fibN = function fib(i) { if(i == 1) return 1; if(i == 2) return 1; return fib(i-1) + fib(i-2); };
Of course you can also use the variable name (fibN in this example) to make the function recursive.
const err1 = function erroriser() { throw Error('error1'); }; const err2 = function() { throw Error('error2'); }; err1(); // Error: error1 debugger eval code:3:9 // erroriser debugger eval code:3 // <anonymous> debugger eval code:1 err2(); // Error: error2 debugger eval code:8:9 // err2 debugger eval code:8 // <anonymous> debugger eval code:1
function foo() { }// no semicolon will be inserted const bar = function() { }// semicolon will be inserted
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The distinction goes a bit deeper than your two examples. MDN provides a good explanation, but I'll give a quick overview:
There are function declarations:
Function declarations must be named.
There are named function expressions:
And there are anonymous function expressions:
As far as I understand, the way you write functions is largely a style choice.
The main differences are:
Of course you can also use the variable name (fibN in this example) to make the function recursive.