MENU
Anonymous Functions & Arrow Functions
Not all functions have a name.
Functions can also be created by a function expression, which can be assigned to a variable.
var f = function () {
console.log(100);
};
f();
(function (x) {
console.log(x);
})(100);100
100
JavaScript now supports arrow functions, which use a shorter syntax, for anonymous functions. The following is identical to the previous example.
var f = () => {
console.log(100);
};
f();
((x) => {
console.log(x);
})(100);100
100
There are a few subtle differences between traditional anonymous functions and arrow functions:
Arrow functions can return a value directly without using the ‘return’ keyword, by omitting the {} immediately after =>.
‘arguments’, ‘constructor’, ‘this’, and ‘super’ are not bound if an arrow function is used.
Arrow functions cannot be constructed with ‘new’.
Arrow functions cannot be generator functions.var f = x => x;
console.log(f(3));
var g = x => { x };
console.log(g(3));
var h = function (x) { x };
console.log(h(3));
var i = x => { a: 1 };
console.log(i(3));
var j = x => ({ a: 1 });
console.log(j(3));var f = function () {
console.log(arguments);
};
f();
var a = new f();
var g = () => console.log(arguments);
// g(); // ReferenceError
// var b = new g(); // TypeError3
undefined
undefined
undefined
{a:1}
[callee: function, Symbol(Symbol.iterator): function]
[callee: function, Symbol(Symbol.iterator): function]
Function expressions assigned to variables are not hoisted, ie. variables assigned with function expressions cannot be used before their declaration.
// f1(); // TypeError
// var f1 = () => { console.log(typeof f1); }
f2();
function f2() {
console.log(typeof f2);
}
// f3(); // TypeError
// if (true) function f3() { console.log(typeof f3); }
if (true) {
f4();
function f4() {
console.log(typeof f4);
}
}function
function
The following shows how to copy an object with only the wanted properties, in a 'clean' way.
var f = ({b, c}) => ({b, c});
var x = f({a: 1, b: 2, c: 3, d: 4});
console.log(x);{b: 2, c: 3}
For security reasons, you cannot use '.name' to retrieve the name of an object method.
function f() {}
console.log(f.name);
var o = {};
o.g = function () {};
console.log(o.g.name);f
(empty string)