Node.js and JavaScript

Continuation Passing Style (CPS)

Functions can take a callback and invoke upon their return value. As a programming style developer should think that a function is never allowed to return to the caller, instead it passes on control to the callback function passed as an argument to it. This provides and effective technique for non-blocking programming. In functional programming, you pass functions around as data, shuffle them around and execute them when needed.

Closure

  • JavaScript provides function level scoping instead of block level scoping
  • Define a function inside an outer function, where inner function has access to variables defined in the outer function.
  • Commonly used in conjunction with anonymous functions
  • Avoid using ’this’ with closure. The outer function may be a function implementation at prototype level and ’this’ has the right context, but ’this’ no longer refers to prototype instance inside inner function

Node.js Event Loop

  • Largest waste in programming comes from I/O
  • Apache is multi-threaded, thread or process per request
  • Nginx and Node.js are not multi-threaded, but are single threaded event based
  • Single thread and no code runs in parallel (no need to synchronize)
  • All I/O is evented and asynchronous
  • An event loop is “an entity that handles and processes external events and converts them into callback invocations”
  • I/O calls are points at which Node.js can switch from one request to another
  • Except I/O calls, Node.js expects all other calls to return quickly. CPU intensive work should be done using WebWorkers
  • Internally Node.js uses libev (event loop) and libio (pooled threads for asynchronous I/O)
  • More details on node.js event loop on this site

Miscellaneous Node.js

  • Define node modules with “module.exports” and use with “require”
  • No circular references allowed with node modules
  • HTTP get request has no body, all data via parameters

for-in loop

  • Iterates over an object
  • Iterates through properties owned by object as well as prototype properties
  • Iterates through functions as well, functions and properties are at same level for JS object
  • Skip prototype properties by using hasOwnProperty()
for (var prop in obj) {
  var type = obj.hasOwnProperty(prop) ? 'own' : 'prototype';
  console.log(prop + ' = ' + obj[prop] + type);
}

for-of loop

  • Introduced in ES6
  • Only iterates over a collection, not object
  • Iterates over the values in a collection and not the keys
  • Collection can be an array, set, list, custom collection object
for (var val of arr) {
  console.log('value = ' + val);
}