Functional Programming in JavaScript
· 阅读需 17 分钟
Agenda
- What is Functional Programming?
- How Functional Programming Differs From Other Paradigms
- Functional Programming in Javascript
- Advantages and Disadvantages of Functional Style
- Interaction of Functional and Object-Oriented Styles
What is Functional Programming?
- Restricted sense, FP means programming without mutable variables, assignments, loops and other imperative control structures
- Wider sense, FP means focusing on the functions
- Particularly, functions can be values that are produced, consumed, and composed.
Functional Programming Languages
Functions in a FP languages are first-class citizens. This means:
- they can be defined anywhere, including inside other function
- like any other values, they can be passed as parameters to functions and returned as results
- as for other values, there exist a set of operators to compose functions
Some languages
Restricted sense:
- Pure Lisp, XSLT, XPath, XQuery, FP
Wider sense:
- JavaScript
- Lisp, Scheme, Racket, Clojure
- SML, F#
- Haskell (full language)
- Scala
OOP vs FP
OO focuses on the differences in the data, while FP concentrates on consistent data structures.
Object-Oriented
- Data and the operations upon it are tightly coupled
- Objects hide their implementation of operations from other objects via their interfaces
- The central model for abstraction is the data itself
- The central activity is composing new objects and extending existing objects by adding new methods to them
Functional
- Data is only loosely coupled to functions
- Functions hide their implementation, and the language’s abstractions speak to functions and the way they are combined or expressed
- The central model for abstraction is the function, not the data structure. The central activity is writing new functions
Declarative vs Imperative
One main distinguishing characteristics of functional programming languages is that they describe what they want done, and not how to do it. OO, inside its methods, still uses mostly imperative techniques.