Bogumil Wrona

IT Consultant | R&D | [...] Solutions

Functional Programming in JavaScript

Image from Wikipedia

functional programming

In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data. Functional programming emphasizes functions that produce results that depend only on their inputs and not on the program stateā€”i.e. pure mathematical functions. It is a declarative programming paradigm, which means programming is done with expressions. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

Read more
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// example 1:
['A', 'B', 'C'].forEach(alert);

// example 2:
var splat = function(fn) {
  return function(array) {
    return fn.apply(null, array);
  };
}, unsplat = function(fn) {
  return function() {
    return fn.call(null, [].slice.call(arguments, 0));
  };
};

var addArrayElements = splat(function(x, y) {
  return x + y;
}),
joinElements = unsplat(function(array) {
  return array.join(' ');
});

console.log(addArrayElements([1, 2]));

console.log(joinElements(1, 2));

Comments