You will often hear that JavaScript is a blank language, where blank is either object-oriented, functional, or general-purpose. This book has focused on JavaScript as a functional language and has gone to great lengths to prove that it is. But the truth is that JavaScript is a general-purpose language, meaning it's fully capable of multiple programming styles. Like Python and F#, JavaScript is multi-paradigm. But unlike those languages, JavaScript's OOP side is prototype-based while most other general-purpose languages are class-based.
In this final chapter, we will relate both functional and object-oriented programming to JavaScript, and see how the two paradigms can complement each other and coexist side-by-side. In this chapter the following topics will be covered:
Better code is the goal. Functional and object-oriented programming are just means to this end.
If object-oriented programming means treating all variables as objects, and functional programming means treating all functions as variables, then can't functions be treated like objects? In JavaScript, they can.
But saying that functional programming means treating functions as variables is somewhat inaccurate. A better way to put it is: functional programming means treating everything as a value, especially functions.
A better way still to describe functional programming may be to call it declarative. Independent of the imperative branch of programming styles, declarative programming expresses the logic of computation required to solve the problem. The computer is told what the problem is rather than the procedure for how to solve it.
Meanwhile, object-oriented programming is derived from the imperative programming style: the computer is given step-by-step instructions for how to solve the problem. OOP mandates that the instructions for computation (methods) and the data they work on (member variables) be organized into units called objects. The only way to access that data is through the object's methods.
So how can these two styles be integrated together?
The point is: OOP and FP can be mixed together and there are several ways to do it. They're not exclusive of each other.