Functional JavaScript

Fun Fun Function is a wonderful video series for learning JavaScript and functional programming. I decided to try my own Map/Reduce filter in JS and uploaded it to my toybox. Some random notes of things I learned along the way:

  • JavaScript has four different variable scoping modifiers: letvarconst, and default (no modifier). let scopes to a block (like a loop), const also scopes to a block and prevents reassignment (though referenced objects may still be mutable), var scopes to a function, and the absence of modifiers indicates a global variable. As always, beware of hoisting which allows a variable to be scoped after it has already been used in code. Not all of these are available in all versions of JavaScript.
  • Running his examples using babel as an ES2015 transpiler is not trivial. To get it to run, I had to do:
    • npm install –save-dev babel-cli
    • npm install –save-dev babel-preset-es2015
    • export PATH=”./node_modules/.bin:$PATH”
    • babel –presets=es2015 medalOTM.js | node
  • JS map takes one parameter and returns one result. This is what you would expect of a mapping or relation.
  • JS reduce is more complex. It reduces the entire pipeline to a single object. This function takes a single callback function parameter and an optional initial value.
    • The initial value can be thought of as the starting point for an object to be built up by the reduce callback over many iterations of the pipeline. Our value is just {}, an empty object.
    • The callback builds up the object. It takes the object to be built up as the first parameter, and it returns a new value for that same object. The second parameter consists of the current pipeline element.
    • The general idea is to use each pipeline element to build up the object.

Functional is fun! And JavaScript is deep!

Thanks to  Kos on StackOverflow for helping me with my basic command-line syntax issues.