JavaScript has always been a functional programming language. You can pass functions as arguments to other functions, and invoke a function that returns a function back to you. The ES6 standard improves JavaScript’s functional programming capabilities by offering a new, succinct syntax for creating functions. In addition, ES6 defines new syntax to offer features closely associated with functional programming, features like iterators and lazy evaluation. Let’s start looking at the new capabilities by looking at the arrow function, which will look familiar to anyone who has worked with CoffeeScript or C# code.
An arrow function doesn’t require the function keyword, or curly braces, or a return statement. However, arrow functions do require a new operator, the =>, which looks like an arrow pointing to the right and which gives these expressions their name. To build an arrow function for adding two numbers, one simply has to write the following.
let add = (x,y) => x + y;
On the left-hand side of the arrow is the parameter list for the function. In this example there are two parameters, x and y. To the right of the arrow is the executable code. In this case, the code returns the sum of x and y. You could think of the arrow as pointing the parameters to the code that uses them.
Invoking an arrow function looks no different than invoking a traditional function.
let result = add(3, 5); expect(result).toBe(8);
Arrow functions that use exactly one function parameter do not need to surround the parameter with parenthesis.
let square = x => x * x;
If an arrow function requires zero parameters, or more than one parameter, then the parenthesis are required.
let add = (x,y) => x + y; // required parens let square = x => x * x; // optional parens let compute = () => square(add(5,3)); // required parens let result = compute(); expect(result).toBe(64);
So far, the examples use a single expression to the right of the arrow operator. When using a single expression, curly braces and return statements are not required. The return value of the function will be the value of the expression.
However, an arrow function may contain a more complex block of statements, but this approach does require braces and an explicit return (if the function wants to return a value).
let add = (x,y) => { var result = x + y; return result; };
In the next post of this series, we’ll look at a special quality of arrow functions, and also see how we can use them in some common scenarios.