1704548093

Javascript - arrow functions


Function expressions can be defined using the fat-arrow syntax. For the most part, arrow functions instantiate function objects that behave in the same manner as their formal function expression counterparts. Anywhere a function expression can be used, an arrow function can also be used: ```js let arrowSum = (a, b) => { return a + b; } let functionExpressionSum = function(a, b) { function(a, b){ return a + b; }; console.log(arrowSum(5, 8)); // 13 console.log(functionExpressionSum(8)); // 13 } ``` Arrow functions are exceptionally useful in inline situations where they offer a more succinct syntax: ```js let ints = [1, 2, 3]; console.log(ints.map(function(i) { return i + 1; })); // [2, 3, 4] console.log(ints.map((i) => { return i + 1 })); // [2, 3, 4] ``` Arrow functions do not require the parentheses if you only want to use a single parameter. If you want to have zero parameters, or more than one parameter, parentheses are required: ```js // Both are valid let double = (x) => { return 2 * x; }; let triple = x => { return 3 * x; }; // Zero parameters require an empty pair of parentheses let getRandom = () => { Math.random(); }; // Multiple parameters require parentheses let sum = (a, b) => { return a + b; }; // Invalid syntax: let multiply = a, b => { return a * b; } ``` Arrow functions also do not require curly braces, but choosing to not use them changes the behavior of the function. Using the curly braces is called the block body syntax and behaves in the same way as a normal function expression in that multiple lines of code can exist inside the arrow function as they would for a normal function expression. If you omit the curly braces, you are using the concise body syntax and are limited to a single line of code, such as an assignment or expression. The value of this line will implicitly return, as demonstrated here: ```js // Both are valid and will return the value let double = (x) => { return 2 * x; }; let triple = (x) => 3 * x; // Assingnment is allowed let value = {}; let setName = (x) => x.name = "Matt"; setName(value); console.log(value.name); // "Matt" // Invalid syntax: multiply = (a, b) => return a * b; ``` Arrow functions, although syntactically succinct, are not suited in several situations. They do not allow the use of arguments, super, or new.target, and cannot be used as a constructor. Additionally, function objects created with the arrow syntax do not have a prototype defined. did you like this post? if so, come and chat more about it in this chat room [https://chat-to.dev/chat?q=javascript-room](https://chat-to.dev/chat?q=javascript-room) or leave your "good or bad" comment below. Thank you

(0) Comments