|
2. Functional Programming benefits from Javascript improvements Functional programming has been up and coming for years, but its impact will increase in 2018 again. Functional Programming (FP) describes the process of building software based on fundamental principles. Principles of functional programming include building software by composing pure functions. Shared state, mutable data and side effects are avoided in FP. Functional code is more predictable, and some say ‘easier’ than object oriented code. It is definitely easier to test. If you have been working in Javascript for a while, you are very likely to have encountered functional programming principles and concepts, which encourage developers to decompose a program into small functions. - // classic
- var numbers = [1, 5, 8, 13];
- var doubledNumbers = [];
- for (var i=0; i < numbers.length; i++) {
- doubledNumbers[i] = numbers[i] * 2;
- }
- // functional
- var numbers = [1, 5, 8, 13];
- var doubledNumbers = numbers.map(function(number) {
- return number * 2;
- });
复制代码
In 2018, Functional Programming especially benefits from the recent Javascript improvements such as ES6 and ES7. Useful for functional programming are the following Javascript improvements: Arrow functions: Arrow functions reduce boilerplate when writing functions.
We can simplify the example from above even more with arrow functions: - // functional ES6
- const numbers = [1, 5, 8, 13];
- const doubledNumbers = numbers.map((number) => number * 2);
复制代码
Object/Array Spread: Object spread makes it really easy to avoid mutating objects, because it is so much easier to create new objects that contain existing values. Here’s an example demonstrating it: - // old school
- var oldState = { email: 'foo@example.com', comment: 'i really like javascript' };
- var newState = {};
- Object.assign(newState, oldState, { ip: '192.168.5.87' });
- // with spread
- const oldState = { email: 'foo@example.com', comment: 'i really like javascript' };
- const newState = { ...oldState, ip: '192.168.5.87' };
复制代码
async/await: Sometimes we do need to call functions that have side effects, even in functional programming – e.g. when we’re talking to our backend. Often we even have multiple calls that depend on each other. First there was callback hell, then came promises, and now async/await has come to make these things even easier.
|