Book Image

Learning Underscore.js

By : Alexandru Vasile Pop
Book Image

Learning Underscore.js

By: Alexandru Vasile Pop

Overview of this book

Table of Contents (14 chapters)
Learning Underscore.js
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Functional programming fundamentals


In the previous example, we transformed an existing dataset into a new structure rather than modifying it (mutating it) by using the two powerful Underscore functions _.map() and _.reduce(). This is a typical example of a functional programming style in action: we use functions also known as higher-order functions that accept other functions as parameters, and we don't alter (mutate) the state of variables such as people and peopleWithAwardAge once they are created—the data that we work with is immutable.

Functional programming (FP) is a declarative programming paradigm in which functions are first class citizens that are treated as values (data), and the application code avoids mutating existing states. In an FP language, you also find that:

  • Functions called higher-order functions can be used to compose other functions by accepting functions as arguments or by returning functions.

  • Functions that don't have side effects are called pure functions, and if they are called repeatedly with the same parameters, they return the same result. They don't have any dependency on data outside their function scope.

There are many aspects of FP such as extensive use of recursion, employing lazy evaluation, and built-in support for pattern matching that are implemented to various degrees in FP languages. Languages such as Erlang, Haskell, Clojure, and F# (to name just a few) are considered functional languages, while languages such as C#, JavaScript, and Java 8 have limited support for a functional programming style. Languages such as Scala are classified as object-functional—a bridge between FP and OOP (object-oriented programming) paradigms.

JavaScript can be used in a functional programming style through its built in support for functions as first class citizens, higher-order functions, by simulating immutability and using its limited recursion capabilities. We will explore JavaScript functional aspects in Chapter 4, Programming Paradigms with Underscore.js and where needed in other chapters.