I want to know the difference between the two.
Can someone please explain with examples?
Also, is the following a function expression, or a function declaration?
_renderAction = ( link, title ) => {
...
}
Declaration - defining named functions
function add(a, b) { return a + b }
Expression - assigning anonymous functions - bad for debugging stack traces
const add = (a, b) => { a + b }
Function Declaration
Function Declaration is creating a named function
function foo() {
return "Hello";
}
Function Expression
A Function Expression defines a function as a part of a larger expression syntax. Functions defined via Functions Expressions can be named or anonymous.
//anonymous function expression
var foo = function() {
return "foo";
}
//named function expression
var bar = function bar() {
return "bar";
}
//named function expression using arrow functions
var baz = () => {
return "baz"
}
//es5
var self = this;
this.nums.forEach(function (v) {
if (v % 5 === 0)
self.fives.push(v);
});
//es6
this.nums.forEach((v) => {
if (v % 5 === 0)
this.fives.push(v)
})
You cannot declare function declaration using ES6 arrow function. Arrow functions are meant to be replacement for traditional function expressions.
// traditional function expression
var foo = function () {
return 'foo';
};
// ES6 arrow function
var foo = () => ({}); // single line must be surrounded with parenthesis
var bar = () => 'bar'; // single line do not need return keyword
var baz = () => {
return 'baz'; // multiline needs explicit return keyword
};
In order to better understand the functions I would highly recommend this article https://kangax.github.io/nfe/
Somasundaram Ayyappan
The only difference between functional expression and declaration is that they come into execution context at different points of time.
Functional declarations are hoisted to the top of the containing scope before the code in that scope is executed.
hello(); // prints 'hello world' function hello() { console.log('hello world'); }Functional expressions are not hoisted to the top, so they can only be executed, if they have already been loaded into the context.
hello(); // Error. Cannot call. hello = function() { console.log('hello world'); }ES6 arrow functions are functional expressions.