Javascript factory functions

Leave a comment

class Dog {
  constructor() {
    this.sound = 'woof'
  talk() {
const sniffles = new Dog(); // outputs 'woof'

Problem with the above class is that as soon as you use it somewhere else, you get a different this.

$('button.myButton').click(  // breaks

The way to fix this is to bind the ‘this’ to be sniffles.


Or you could do this

$('button.myButton').click( _ => )

A better way – function factories

In JavaScript we don’t have to use classes. Instead we can use factory functions.

Here dog is simply a function.

const dog = () => {

  const sound = 'woof'
  return {
    talk: () => console.log(sound)

const sniffles = dog() // woof

This is just a variable, ‘sound’, and then return a simple object literal with one property ‘talk’. And because of closures the talk function has access to the variable sound.

This also has the added benefit in that variable sound is private. No one else can see it except this function.

So the advantages here are:
– privateness of variables
– no explicit bind necessary
– and no magical ‘this’ to worry about because it’s all constructed in the right way


JavaScript Scope

Leave a comment

When you start typing in JS you are in global scope.

Screen Shot 2017-08-29 at 2.22.08 PM.png

Variables defined inside a function are in the local scope. Meaning they have a different scope for every call of that function.

Screen Shot 2017-08-29 at 2.24.02 PM.png

Block statements

Contrary to the ‘var’ keyword, ‘let’ and ‘const’ support the declaration of local scope inside block statements.

Screen Shot 2017-08-29 at 2.27.18 PM.png

Difference between let and const?

‘const’ is a signal that the identifier won’t be reassigned.
‘let’ is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm.

Both have block statement scope.


Many developers think scope and context are the same thing. They are not. Scope is what we talked about previously. Context is ued to refer to the value of ‘this’ in some particular part of your code.

Scope refers to the visibility of variables and context refers to the value of ‘this’.

Lexical Scope

Means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as Static Scope.

Screen Shot 2017-08-29 at 2.38.44 PM.png


Closures are closely related to Lexical Scope. A closure is created when an inner function tries to access the scope chain of its outer function. Closures contain their own scope chain, their parents, and the global scope.

When you return an inner function from a function, that returned function will not be called when you try to call the outer function. You must first save the invocation of the outer function in a separate variables and then call the variable as a function.

Screen Shot 2017-08-29 at 2.43.03 PM.png

Key thing to note here is that ‘greetLetter’ can access the name variable in the greet function even after it has returned. One way to call the returned function without doing the variable assignment is to call it with () x2 like this.

Screen Shot 2017-08-29 at 2.45.43 PM.png

Note: This still works.

Screen Shot 2017-08-30 at 7.23.16 AM.png

The difference in the previous example is the return statement. It only gets invoked when you do the ()().

Public and Private Scope

JS doesn’t have concepts found public, protected, private. Instead it emulates these features using closures. Which is basically nothing more than locally scope variables and functions.

Screen Shot 2017-08-30 at 7.15.03 AM.png

The Module Pattern

Screen Shot 2017-08-30 at 7.15.57 AM.png

This module pattern is a way to define Objects (functions) in JS that exposes public methods via a return statement while keeping private methods inside.

Screen Shot 2017-08-30 at 7.18.07 AM.png

Immediately-Invoked Function Expression (IIFE)

Screen Shot 2017-08-30 at 7.19.40 AM.png

Changing Context with .call(), .apply(), and .bind()

Call and Apply functions change the context of the function you are calling.

Screen Shot 2017-08-30 at 7.24.52 AM.png

The difference between .call() and .apply() is that in call you pass the arguments as a comma separated list, while in apply you pass them as an array.

Screen Shot 2017-08-30 at 7.28.19 AM.png

JavaScript Value vs Reference

Leave a comment

JavaScript has 5 data types that are copied by value. We call these primitives:
– Boolean
– null
– undefined
– String
– Number

And 3 data types that are copied by reference. We call these Objects:
– Array
– Function
– Object

Pure functions

Any function that doesn’t affect anything outside it’s outside scope is called a pure function. A function made up of primitives is a pure function. An Array passed in as an argument, that gets something pushed onto it, would affect the outside scope array. It’s change would persist to the outer scope and can lead to bugs that are hard to track down.

That’s why and Array.filter return copies of the Array they operate on and were written as pure functions.


See if you can decode what’s going on here.

Screen Shot 2017-08-29 at 1.45.07 PM.png

We start off with personObj1, pass it into the function, assign it an age of 30, and then point it to a new object instance before returning and assigning it to a new variable.

Here is the actual output

Screen Shot 2017-08-29 at 1.46.42 PM.png

Get it? personObj1 is passed by reference to the method. So method has a pointer to personObj1 and assigns it a new age of 25. It’s done.

Screen Shot 2017-08-29 at 1.47.56 PM.png

This next line of code is the tricky one.

Screen Shot 2017-08-29 at 1.48.30 PM.png

This chunk of code reassigns the pointer that was pointing to personObj1 to a new object – John 50 and returns it.

Screen Shot 2017-08-29 at 1.49.25 PM.png

The reassignment does not change personObj1. It remains intact. person has a new reference because it was reassigned. But reassign doesn’t change original. The equivalent above would be the following.

Screen Shot 2017-08-29 at 1.51.17 PM.png

Links that help

These notes were based on the excellent links found here:

Template literals

Leave a comment

I was doing some reactjs examples and I came across this strange syntax for invoking JS. Something called a template literal.

Screen Shot 2017-08-29 at 8.03.23 AM.png

Screen Shot 2017-08-29 at 8.04.30 AM.png

JavaScript arguments and Rest parameter syntax

Leave a comment


Here is a basic JS function

Screen Shot 2017-08-29 at 7.40.12 AM.png

Functions have parameters, but they also have access to additional variable called arguments, which is an array-like object holding all of the values passed to the function.

Here is how we could re-write the function to take as many arguments as we want

Screen Shot 2017-08-29 at 7.45.10 AM.png

This is useful, but a little verbose. To diminish the code a bit more we can substitute the arguments array with Rest parameter syntax.

In this way we can pass in any number of arguments while keeping our code minimal.

Screen Shot 2017-08-29 at 7.52.47 AM.png

Rest in this context means ‘rest of the arguments’.


JS let’s you create anonymous functions

Screen Shot 2017-08-29 at 7.55.34 AM.png

But what if you want to call a function recursively? JS lets you create named function expressions (IIFEs or Immediately Invoked Function Expressions) like so.

Screen Shot 2017-08-29 at 7.57.35 AM.png

Links that help

JavaScript Arrow functions

Leave a comment

These are functionally equivalent

Screen Shot 2017-08-29 at 6.39.46 AM.png

Screen Shot 2017-08-29 at 6.39.51 AM.png

Note the difference: In arrow functions the stuff put in the () are the method arguments and the stuff that comes after ({ // }) is the return statement. That’s it.

The first method uses the new JavaScript arrow function. And it was created to do two things.

  1. Shorter functions.
  2. The non-binding of this.

Shorter functions

Normally in JS you pass functions as parameters using a function expression. Something that looks like this on i.e. (which returns a new array with the results of calling the provide method on every element in the calling array).

Screen Shot 2017-08-29 at 6.45.19 AM.png

This is called a function expression and it’s how you can define functions that can be passed as arguments to methods.

ES2015 defined a shorter way of doing this. Something called arrow functions.

Screen Shot 2017-08-29 at 6.50.09 AM.png

With arrow functions, instead of defining everything with the keyword function, you can just create a lambda like expression like this.

Screen Shot 2017-08-29 at 6.51.09 AM.png

The way to read this is (parameters) => { // code }

i.e. you declare the parameters you need passed in in the () and then you use them in your code. This leads to some nicer more terse code.

No binding of this

Until arrow functions, every new function define its own ‘this’ value. This proved to be annoying in OO style programming.

Screen Shot 2017-08-29 at 6.59.24 AM.png

In ECMAScript 3/5, this issue was fixable by assigning another value to ‘this’ that could be closed over.

Screen Shot 2017-08-29 at 7.01.30 AM.png

Alternatively, a bound function could be created so that a preassigned ‘this’ value would be passed to the bound target function.

An arrow function does not create its own ‘this’, the ‘this’ value of the enclosing execution context is used instead. Thus the ‘this’ value in ‘setInternal’ has the same value as ‘this’ in the enclosing function.

Screen Shot 2017-08-29 at 7.18.16 AM.png

No binding of arguments

Arrow functions do not bind an arguments object. Thus, in this example, arguments is simple a reference to the same name in the enclosing scope.

Screen Shot 2017-08-29 at 7.24.00 AM.png

Here we define a variable 42, create a method out of it using () => arrow function, and then execute the method.

Screen Shot 2017-08-29 at 7.25.03 AM.png

Here we define a function foo(), define a variable method f (using the args rest parameters) and then simply return the first argument.

Arrow functions used as methods

As mentioned previously, arrow functions should not be used as methods, but rather only passed as non-method functions. Here’s what happens when used as method.

Screen Shot 2017-08-29 at 7.28.01 AM.png

Because the method ‘b’ does not bind ‘this’, ‘this’ is undefined.

You also can’t use arrow functions as constructors or access their prototype property.

Screen Shot 2017-08-29 at 7.29.52 AM.png


These are functionally equivalent.

Screen Shot 2017-08-31 at 6.10.14 AM.png

Arrow functions for beginners

Screen Shot 2017-08-31 at 7.21.13 AM.png

Screen Shot 2017-08-31 at 7.21.45 AM.png

Screen Shot 2017-08-31 at 7.21.51 AM.png

Screen Shot 2017-08-31 at 7.21.58 AM.png

Screen Shot 2017-08-31 at 7.22.05 AM.png

Screen Shot 2017-08-31 at 7.22.12 AM.png

Screen Shot 2017-08-31 at 7.22.25 AM.png

Screen Shot 2017-08-31 at 7.23.51 AM.png


Screen Shot 2017-08-31 at 7.28.33 AM

Screen Shot 2017-08-31 at 7.28.48 AM

Screen Shot 2017-08-31 at 7.29.10 AM

Screen Shot 2017-08-31 at 7.29.43 AM

Screen Shot 2017-08-31 at 7.30.14 AM

Screen Shot 2017-08-31 at 7.31.33 AM

Screen Shot 2017-08-31 at 7.26.21 AM.png

Links that help
Arrow functions
Function expression
Arrow functions for beginners

Javascript Model-View-Controller example


When I first got into Javascript, it wasn’t obvious to me how best to use the language to do a simple model-view-controller.

I’ve heard of backbone, spine, and some other javascript mvc frameworks, but I just wanted to start with something really simple. My friend Jonas came up with a good example showing how our thinking has evolved after building some stuff.

Option 1: Prototype

In the prototype method you define your functions using the javascript prototype construct and then make use of ‘this’ and ‘self’ to make sure you are calling your methods with the right javascript context.

This is how we first stared doing simple mvc.


var FormModel = function(){};

FormModel.prototype.getInputText = function(){
   return $('#inputtext').val();

FormModel.prototype.setInputText = function(value){


var FormController = function(pModel){

    this.model = pModel || new FormModel();
    this.fill_clicked = function(){
        this.model.setInputText('Hello World');

    this.clear_clicked = function(){

FormController.prototype.init = function(){

    var self = this;

    $('#fillbutton').click(function(){ self.fill_clicked(); });
    $('#clearbutton').click(function(){ self.clear_clicked(); });

FormController.prototype.getModel = function(){
    return this.model;

It’s nice. It works. You don’t need to worry about state (it’s all in the model). But you do need to watch context (this, that, and self) and it’s easy to get wrong if you aren’t careful.

Option 2: Literal method

In the literal method, you use the javascript literal construct to keep most internal methods private, and then only expose those you want publicly consumed in the return statement.


var FormModel = function(){

    function getInputText(){
       return $('#inputtext').val();

    function setInputText(value){

    return {
        getInputText : getInputText,
        setInputText : setInputText


var FormController = function(pModel){

    var model = pModel || new FormModel();

    function fill_clicked(){
        model.setInputText('Hello World');

    function clear_clicked(){

    function init(){

        $('#fillbutton').click(function(){ fill_clicked(); });
        $('#clearbutton').click(function(){ clear_clicked(); });

    return {
        init: init,
        model : model

I think it’s elegant and nice. And I didn’t even know you could use a return statement like that in Javascript.

The advantage of this method is you don’t have to worry so much about getting the context wrong (this, that and self) as it’s all in the same context.

And it’s just easier on the eyes for me as it more closely resembles the classical OO model I am used to in Java and C#.

You can hook these up in view a test page as follows:


        <script type="text/javascript" src="jquery-1.6.1.min.js"></script>

        <!-- Using function returning an Object literal (my preference) -->
        <script type="text/javascript" src="js/controllers/FormController_literal.js"></script>
        <script type="text/javascript" src="js/models/FormModel_literal.js"></script>

        <!-- Using Prototype -->
        <!--<script type="text/javascript" src="js/controllers/FormController_prototype.js" ></script>-->
        <!--<script type="text/javascript" src="js/models/FormModel_prototype.js"></script>-->

        <script type="text/javascript">

            $(document).ready(function() {
                new FormController().init();



        <input type="text" id="inputtext" name="inputtext" value="" />
        <input type="button" id="fillbutton" value="Fill with Text"/>
        <input type="button" id="clearbutton" value="Clear"/>


So while both methods will work, we are currently leaning towards option 2 (the literal method).

It just seems cleaner, less stuff to worry about, and it looks good. Of course being relatively new to hard core javascript, and still looking for better ways, we reserve the right to change our minds tomorrow.

If you have any tips, better ideas, or feedback, we’d love to hear them.

Nice write up along similar lines from Ola Bini.

Older Entries

%d bloggers like this: