Functional Nature of Javascript

This post includes some of my notes from reading the first three chapters of the book Secrets of the Javascript Ninja co-authored by the JQuery library creator John Resig.

The first part of the book concerns itself on Javascript’s functional nature and I will be discussing the capabilities of functions in this post.

Why use a Functional Language?

In Javascript, a function is a “primary modular unit of execution”. The language has been used principally as a browser scripting language. Hence having functions to be “versatile and powerful gives us a great level of flexibility” in terms of writing our code.

Functions in Javascript are considered first-class objects because they have the following capabilities:

Can be created via literals e.g

simple function declaration

Can be assigned to variables, array entries, and properties of other objects e.g

Example 1: Anonymous Function is assigned to the variable “variableFunc”. Example 2: testplayerDetailsFunc becomes a method for objects testPlayer1 and testPlayer2. Method is invoked using the property name testplayerDetails on the object

Can be passed as arguments to functions e.g

Can be returned as values from other functions e.g

Can possess properties that can be dynamically created and assigned e.g

In non functional object oriented languages, methods cannot exit on their own and cannot be passed as arguments to other methods. They have to be declared as members of an object. Although C++ and Java in the recent years have developed the concept of lambda functions that are similar to Javascript’s anonymous functions.

Anonymous functions are used in web programming to not pollute the global namespace. It is a better practice to create lots of little functions and pass them around to other functions.

Hence in this post through the use of examples I was able to demonstrate the power of functional programming in Javascript!