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.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var f = function(){console.log(100);}f(); // 100(function(x){console.log(x);})(100); // 100
</script></body><html>
JavaScript now supports arrow functions, which use a shorter syntax, for anonymous functions. The following is identical to the previous example.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var f = ()=>{console.log(100);}f(); // 100((x)=>{console.log(x);})(100); // 100
</script></body><html>
RESETRUNFULL
<!DOCTYPE html><html><body><script>
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.
</script></body><html>
<!DOCTYPE html><html><body><script>
var f=x=>x;
console.log(f(3)); // 3var g=x=>{x};
console.log(g(3)); // undefinedvar h=function(x){x};console.log(h(3)); // undefinedvar i=x=>{a:1};
console.log(i(3)); // undefinedvar j=x=>({a:1});
console.log(j(3)); // {a:1}
</script></body><html>
<!DOCTYPE html><html><body><script>
var f = function(){console.log(arguments);};f(); var a = new f();// [callee: function, Symbol(Symbol.iterator): function]// [callee: function, Symbol(Symbol.iterator): function]var g = ()=>console.log(arguments);//g(); // ReferenceError//var b = new g(); // TypeError
</script></body><html>
Function expressions assigned to variables are not hoisted, ie. variables assigned with function expressions cannot be used before their declaration.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
//f1(); var f1 = ()=>{console.log(typeof f1);} // TypeErrorf2(); function f2(){console.log(typeof f2);} // function// f3(); if (true) function f3(){console.log(typeof f3);} // TypeErrorif (true){f4();function f4(){console.log(typeof f4);}} // function
</script></body><html>
The following shows how to copy an object with only the wanted properties, in a 'clean' way.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var f = ({b, c}) => ({b, c});var x = f({a:1,b:2,c:3,d:4});console.log(x); //{b: 2, c: 3}
</script></body><html>
For security reasons, you cannot use '.name' to retrieve the name of an object method.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function f(){}console.log(f.name); // fvar o = {};o.g = function(){}console.log(o.g.name); // (empty string)
</script></body><html>