For an implementation attempt I wrote this: How to Implement Google Tag Manager in Svelte, in Functional Programming(?).
Functions as first-class citizens
When Brendan Eich created JS he intended to make Scheme for the browser, but Java was really popular…He was persuaded to make the syntax C-like. Eich still implemented functions as first-class—a necessity for a functional programming language.
An early computer printout of Christopher Strachey in the Bodleian Library, Oxford. Christopher Strachey coined the term “first-class functions”. (Figure from Wikipedia)
[First-class functions] means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.
Higher order functions are functions that takes a function as an argument and/or return a function.
list.filter(item => item.includeItem);
With ES6, passing functions as arguments became more normal with the powerful
map and other Array methods, “which takes, as its arguments, a function and a list, and returns the list formed by applying the function to each member of the list” (Wikipedia).
Another concept of functional programming is pure functions.
A pure function must satisfy both of the following properties:
- Referential transparency: The function always gives the same return value for the same arguments. This means that the function cannot depend on any mutable state.
- Side-effect free: The function cannot cause any side effects. Side effects may include I/O (e.g., writing to the console or a log file), modifying a mutable object, reassigning a variable, etc.
Also, a pure function should return something, and that something should be used.
Immutability means that within the scope of a function variables should be immutable—unchangeable from outside the function.
- Declare using
splice()for arrays. Basically everything that mutates a variable.
Nowadays I much rather use a higher-order function than a loop. The latter is imperative programming, giving the machine steps of what to do. E.g., using Array functions is declarative programming where the steps for the machine is abstracted away, or by using recursion.