A function is a subprogram designed to perform a particular task. Functions combined, become the main “building blocks” of the program.
JavaScript has many built-in/ anonymous functions. We can create functions of our own as well.
Arrow functions, introduced in the latest version of JavaScript ES6, provides a concise way to write functions in JavaScript.
"Var", which is a way to declare a variable, is used in ES5. Functions are written using the "function" keyword with arguments. These functions have existed since the beginning of JavaScript.
ES6 allows you to declare a variable using "const" and "let". Arrow functions can be used, making writing code shorter! The same code(top) can be written shorter with the arrow method (bottom). As shown in the diagram, a lot of the syntax required in ES5 is optional for the ES6 arrow method. The parenthesis is optional when there is one argument, and the braces and keyword "return" are optional.
Named Functions into Arrow functions:
Example 1:
Above is a regular function (ES5). The function takes a name "message" and returns "Green Light District". When we "console.log(message())", the message shows up in the console.
Above is the same function, using the arrow method. It has the same output but shorter code! In order to change the first function into an arrow function, the function name has to be turned into a variable. The arrow is created with the equal sign and greater than symbol, "=>". The string "Green Light District" is being returned implicitly after the arrow symbol.
Example 2:
Another function that takes in an argument and interpolates the argument with a string in the result. Below is the function turned into an arrow function:
Example 3:
The function above is an arrow function taking in two arguments. There will be two argument within the parenthesis, after the variable is declared. Both "a" and "b" will be interpolated after the arrow sign.
As I mentioned before, JavaScript has many built-in or anonymous functions. These functions can also be written as arrow functions.
Example:
Given an array of objects, the .map method can be used to take in an array of numbers and creates a new array containing the return value of your choice.
This arrow function, as the others above have replaced the "function" keyword effectively with the arrow "=>" and had optional syntax's, making concise code.
Top comments (0)