Mastering JavaScript Functional Programming
上QQ阅读APP看书,第一时间看更新

JavaScript as a tool

What is JS? If you consider popularity indices such as the ones at www.tiobe.com/tiobe-index/ or  http://pypl.github.io/PYPL.html, you'll find that JS consistently is in the top ten of popularity. From a more academic point of view, the language is sort of a mixture, with features from several different languages. Several libraries helped the growth of the language, by providing features that weren't so easily available, as classes and inheritance (today's version of JS does support classes, but that was not the case not too long ago) that otherwise had to be simulated by doing some prototype tricks.

The name JavaScript was chosen to take advantage of the popularity of Java — just as a marketing ploy! Its first name was Mocha; then, LiveScript, and only then, JavaScript.

JS has grown to be incredibly powerful. But, as with all power tools, it gives you a way to produce great solutions, and also to do great harm. FP could be considered to be a way to reduce or leave aside some of the worst parts of the language and focus on working in a safer, better way. However, due to the immense amount of existing JS code, you cannot expect large reworkings of the language that would cause most sites to fail. You must learn to live on with the good and the bad, and simply avoid the latter parts.

In addition, JS has a broad variety of available libraries that complete or extend the language in many ways. In this book, we'll be focusing on using JS on its own, but we will make references to existing, available code.

If we ask if JS is actually functional, the answer will be, once again, sorta. JS can be considered to be functional, because of several features such as firstclass functions, anonymous functions, recursion, and closures -- we'll get back to this later. On the other hand, JS has plenty of non–FP aspects, such as side effects (impurity), mutable objects, and practical limits to recursion. So, when programming in a functional way, we'll be taking advantage of all the relevant JS language features, and we'll try to minimize the problems caused by the more conventional parts of the language. In this sense, JS will or won't be functional, depending on your programming style!

If you want to use FP, you should decide upon which language to use. However, opting for fully functional languages may not be so wise. Today, developing code isn't as simple as just using a language: you will surely require frameworks, libraries, and other sundry tools. If we can take advantage of all the provided tools, but at the same time introduce FP ways of working in our code, we'll be getting the best of both worlds — and never mind if JS is or isn't functional!