JavaScript, Languages, Programming Languages

JavaScript’s Function.prototype.bind


The bind function allows you to set the context with which a function will execute. It takes in a ‘context object and returns a new function which has its context set to the passed in object. The variadic method, which exists on all function objects, provides a workaround for the annoying and elusive ‘this’ context issue in JavaScript.

As web developers; we all nearly need to create references to object methods at some time or the other. The annoying thing is that the original context is uusally lost when we need it most! Let’s see how bind can help in these scenarios.

var obj = {
    val: 10,
    getVal: function () {
         return this.val;
    }
};

obj.getVal();
//10

var valGetter = obj.getVal;
valGetter();
//undefined

var boundValGetter = valGetter.bind(obj);
boundValGetter();
//10

Function Signature

Function.bind(thisObj, arg1, arg2,…)

thisObj refers to the new context for the function. However if the newly returned function is used as a constructor (i.e. called using the new operator), the this context will be a new empty object as expected.

arg1, arg2,… are extra parameters that are prepended to the list of arguments that the newly bound function is called with. Assuming you declare two arguments in the original bind call and then pass three new arguments to the returned bound function, then the two original bound arguments appear before the three newly passed in arguments.

var fn = function () {};
var bound = fn.bind(window, 1,2);

#equivalent forms
bound(3);
fn.call(window, 1,2,3)

If the bound function is invoked as a constructor, then the bound arguments are still passed on.

Uses

The most common application would be to avoid the use of the ‘that = this’ pattern in JavaScript. This is especially the case when you need to pass in context to event handlers, use anonymous functions or do something similar.

var ordExample = {
     log : function () {
           console.log('logger called');
     },
     asyncCall : function (callback) {
          //...
          callback();
     },
     useAsync : function () {
          var that = this;
          this.asyncCall(function () {
               that.log();
          });
     }
}

//Bind form
var bindExample = {
     log : function () {
          console.log('logger called');
     },
     asyncCall : function (callback) {
          //...
          callback();
     },
     useAsync : function () {
          this.asyncCall(function () {
               this.log();
          }.bind(this));
     }
}

ordExample.useAsync();
//logger called
bindExample.useAsync();
//logger called

As seen from the example above, we can use this in all sort of scenarios – from timers, Ajax callback handlers, event handlers, custom objects etc.

Issues

You cannot unbind after binding a function; anytime you call the Function.prototype.bind, you get a new function which has its ‘this’ context already prefixed to the pre-supplied value.

var fn = function () {};
console.log(fn.bind(this)===fn.bind(this));
//false

Ben Cowboy Alman has written a Function.protoype.unbind polyfill here.

The other issue is that there is some overhead with using bind; it adds some overhead and is not as optimal as using the ‘this = that‘ approach (variable vs function). Here is a jsperf run for four various bind styles.

So that’s it; now go bind some functions.

Standard
Software Development, Version Control

I Git! Stashing Explained


Imagine these scenarios when working in Git:

1. You do not want to commit your unfinished work but need to switch to a new branch to start some new work immediately.

2. A git pull results in conflicts however you do not want to commit local changes yet.

3. You realize you have worked in the wrong branch and want to move your uncommitted work to the right branch.

The Git stash command would help in these situations – it takes all the changes in your working directory and puts them in a stack you can always access later.

The command does two things:

1. It saves the working directory and index to a safe temporary place (the latest stash is usually at .git/refs/stash).

2. Then, it restores the working directory and index to the most recent commit (i.e. the commit pointed to by HEAD).

Thus, you can go ahead and switch to a new branch or complete the pull after a stash.

git stash

It might fail if you do not have any commit in the repository. You need to have at least a single revision as shown below:

git init
git stash
//fatal: Bad revision 'HEAD'
//fatal: Bad revision 'HEAD'
//fatal: Needed a single revision
//You do not have the initial commit yet

Now, let’s try again after making some commits to the repository

echo "Temp" > temp
git add temp
git commit -m "stash first commit"
git stash
//No local changes to save

Next, lets stash some temporary changes; note that stashing does not save changes that are being tracked (more on tracking vs staging areas in an upcoming post insha Allaah).

echo "staging" >> temp

#Add changes to staging area
git add temp
git status
#Should show staged changes to temp

echo "tracking" > tracking
git status
#shows staged and tracked changes

git stash
#Saved working directory and index state
#WIP on master: 2038ddd stash

git status
#clean staging area
#Tracked changes unmodified

Using stashed work

The stash is a stack and can contain multiple changes. The following commands show how to interact with it.

#list all stashed changes
git stash list

#apply the topmost stashed changes
git stash apply

#Show applied changes
git status

#Stash still has applied stash
git stash list

#Pop the stashed change at ref 2
git stash pop stash@{2}

#Show applied changes
git status

#Verify stash@{2} was removed
git stash list

#delete stash at ref 3
git stash drop stash@{3}

#Delete all stash entries
git stash clear

The difference between apply and pop is simple: apply is non-destructive, it preserves the stashed entry on the stack while pop will remove it. The pop command can be seen as an apply + drop combo. And yes, it is possible to create a new branch from a stashed entry.

# create a new branch from stash
git stash branch newBranchForStash

It automatically checks out the branch too; but make sure the branch name is unique!

Done! Happy Stashing!!

Standard
JavaScript, Languages, Programming Languages

Quirky Quirky JavaScript: Episode One


JavaScript is an awesome language however it exhibits some quirks; this posts examines some of these fine odd aspects of JS; dive in, you’ll love it!

First, what do these 3 code snippets do?

3.toString();

void 0;

(3,4);

If your answers were ‘SyntaxError: Unexpected token ILLEGAL‘, undefined and 4; then give yourself a pat on the back! You nailed it. Now, lets find out why…

1. 3.toString() – Decimal Point or Number method?

This throws a SyntaxError because the code is confusing to the JavaScript Interpreter. The dot after the 3 is ambiguous –  does it signify a decimal point or a method of the Number object?

JavaScript chooses to interpret it as a decimal number, it thus expects valid decimal digits after the dot – e.g. 3.0, 3.1, 3.999999999 etc. When it finds ‘toString’ instead of a digit; the interpreter goes KA-Boom! SyntaxError!!

Workarounds

Here are a couple of ways to fix this:

1. Wrap the decimal in parentheses – this forces it to be seen as a single expression; e.g. (3.).toString();.

2. Add a decimal digit after the dot – 3.1.toString(); this removes all ambiguity about the dots: the first is the decimal point while the second is a method from the Number object (after all, there can’t be two decimal points in a single number).

3. Use 3..toString(); this is less readable but works too. As explained above, 3. is a float while 3 is an integer; thus any dots appearing after 3. will definitely refer to a method of the Number object.

2. Void 0 – The Void Operator

This evaluates the expression that appears after it and always returns undefined. void 1, void 2 or void “blah” also work (any expression is fine) however the convention is to stick to void 0.

This can be used to ensure that undefined is always undefined (in JS land, clobbering window.undefined  is fair game). Since the return value of the void operator is guaranteed to be undefined; functions like the one below are employed as safeguards. In fact a couple of JS libraries (e.g. underscore) use this technique quite often.


undefined = "defined"; //Gotcha!

function getUndefined() {
    return void 0;
}

The void operator is also used in bookmarklets (bookmarks that allow you to do stuff by executing JavaScript) and while using the javascript:url coding style (which I assume no one uses…).

In these scenarios; returning a value will make the browser navigate to the returned value. Thus evaluating the expression in a void call kills two birds with a stone – you get to evaluate your expression while still preventing the browser from navigating away.

3. (3,4) – The Comma Operator

The comma operator takes a series of expressions, evaluates all of them from left to right and returns the result of the last expression. This can be leveraged in evaluating multiple scenarios where only a single expression is expected. So you can do something like 2,3,4,5,”wow… this is valid JavaScript!”, 9 and the result will be 9! Impressive huh?

The comma operator should not be confused with the comma separator in variable declarations; that comma separator allows the combination of multiple var declarations into a single one.

The comma operator only occurs within expressions as shown below:


var x = 2,3,4,5,"valid JavaScript!",9
//SyntaxError: Unexpected number

//Wrap in expression
var x = (2,3,4,5,"valid JavaScript!",9)
console.log(x);
//9

If you are pedantic then you find it pleasing to know that the comma operator in JavaScript was taken from the C comma operator

Extra Bonus

The typeof operator is a unary operator but calling it like a function (i.e. typeof(3) ) seems to work perfectly. Strange?

Here is what I believe happens:

typeof(3) -> typeof   (3) -> typeof  3 -> Number

The same reasoning would apply to the void operator; and that’s why you have usages like void (0).

There you go! Now go spread some JavaScript love!! :D

Standard
Computer Science, Languages, Learning, Programming Languages

Programming Paradigms: An Introduction


A programming paradigm is a way of programming, a style of solving problems and thinking about the domain. Languages directly or indirectly influence programming style; for example, Haskell is purely functional while Python allows a blend of OOP, functional and imperative programming.

Even though most new languages are multi-paradigm, they usually make it easiest to program in a single paradigm; C programs can be written in a functional programming style (instead of the orthodox procedural fashion) –  it is just extremely difficult. Ever wondered why classes are needed to add two numbers in OOP Java?

Paradigms can be viewed as abstractions and metaphors for modelling problems – logic programs can be viewed as theorem solvers; functional programs rely on mathematical models while OOP models real-life objects and their interactions.

Nearly every standard problem can be solved using any of the programming paradigms however some problems are best solved using some paradigms (e.g. recursion vs loops). Thus knowing many paradigms helps programmers in producing very neat and elegant solutions; since they know different ways of solving problems and modelling domains.

Let’s take a shallow dive into some of the popular paradigms.

1. Imperative Programming

imperate: Done by express direction, not involuntary; commanded

In the imperative paradigm, programs are written as a series of instructions that affect global state. It is conceptually similar to cooking recipes which strictly list the steps in preparing a dish.

The imperative paradigm was quite popular until Dijkstra published his famous ‘GOTO considered harmful‘ letter. This fueled the adoption of the structured programming paradigm (albeit at the detriment of imperative programming).

2. Structured Programming

Structured programming is somewhat similar to imperative programming however control flow is defined in terms of loops, subroutines and conditionals; this distinguishes it from the imperative model of jumping around at the heck and bequest of every GOTO call.

The introduction of lexical scoping also helps to prevent the inadvertent overwriting of variables in the global scope.

3. Declarative Programming

Declarative programs have implicit execution: programs say what they want but not how the results should be gotten. SQL is a popular example, have you ever wondered how the SQL engine is able to calculate sums, averages, max etc.

A conceptual example is that of a manager declaring sales targets for his marketing team: the team is smart enough to figure out heuristics and also to go do it on their own (hopefully within ethical and legal limits).

4. Functional Programming (FP)

The functional programming paradigm is a subset of the declarative paradigm. All computation is done using functions – it attempts to do away with the use of variables and value assignments.

Pure functional programs are written as a combination of function calls which have no side effects and return the same result every time they are called with the same input no matter the environment. The elegance of FP comes from the use of higher-order functions (functions which can accept/return other functions e.g. differentiation/integration in the maths domain), referential transparency and high levels of abstraction.

On the other hand, some concepts might be inefficient (e.g. Y combinator) or ugly.

5. Object Oriented Programming (OOP)

This is probably the most popular and probably most widely-used of all programming paradigms. Object oriented programming is built on four major principles – encapsulation, polymorphism, inheritance and data abstraction.

OOP allows the creation of abstract models that mirror real-life objects’ interactions and behaviour. This enables the creation of huge complex software systems having intricate interactions such as state preservation, communication exchanges and behaviour handling.

There are two flavours: classical (where objects are defined and share their characteristics and behaviour based on a class’ blueprint) and prototypical (objects get their behaviour and characteristics from an original prototype object).

Conclusion

Some other paradigms include the event-driven where program respond to events (think web apps) while the logical programming paradigm tries to infer the solution when it is given a set of constraints and or conditions.

Upcoming posts would insha Allaah take a more thorough look at some of the popular paradigms.

Standard
Design Patterns, JavaScript, Languages

The Immediately Invoked Function Expression


The Immediately Invoked Function Expression (IIFE, pronounced iffy) is a named/anonymous function expression that is executed immediately after its declaration.

It typically involves appending the function invocation operator ‘()’ to the end of a function expression; this triggers its immediate invocation.

(function () {
    console.log("IIFE!");
})();

//Another style
(function () {
    console.log("IIFE!");
}());

//passing in variables
(function ($) {
    console.log('jQuery:', $);
})(jQuery);

Some background

The IIFE used to be wrongly regarded as a Self Invoked Anonymous Function (SIAF) until Ben “Cowboy” Alman (of GruntJS and tinypubsub fame) suggested the more appropriate IIFE term. An IIFE does not have to be self-executing or anonymous all the time.

//Named function expression
!function name() {
    console.log("IIFE!");
}();

Self Invoked Anonymous Functions (SIAF)

A self-executing function is a function that executes itself, a self-executing function would usually have this pattern:

function selfExecFn() {
     selfExecFn();
}

Anonymous functions are function expressions with no identifiers/names.

(function () {
    //...code here
})()

A SIAF has to be both self-executing and anonymous right? Anonymous functions have no identifier, thus the callee property of the arguments object is used to achieve self-invocation - arguments.callee always refers to the currently executing function.

Combining all these, a self-invoked anonymous function will look like the code snippet below:

(function () {
    arguments.callee();
})()

Note: arguments.callee is going to be deprecated and does not work in EcmaScript 5′s strict mode. So technically, it’ll be impossible to create a SIAF!

Aside, I wonder why they are not called recursive anonymous functions – RAF which sounds much more apt.

What are the uses of the IIFE?

1. Data encapsulation is probably the biggest benefit. IIFEs help to prevent properties in the global object from getting overwritten and/or polluted while protecting the local variables from external parties. This is what makes it possible to use libraries like jQuery and Prototype which both override the $ variable side by side.

2. IIFEs create closures  which can be used in turn to simulate ‘private’ variables in JavaScript.

3. Comes in handy for the module pattern.

Want to achieve a deeper understanding of JavaScript? Here are a couple more posts:

1. The JavaScript Function

2. Three Important JavaScript Concepts

3. Defining JavaScript Functions

Standard
JavaScript, Languages, Learning, Miscellaneous

Defining JavaScript Functions


There are many ways to create functions in JavaScript; some styles are quite popular e.g. the function declaration and function expression while others are not.

//function samples
function declaration () {};
var funcExpression = function () {};
var namedFuncExpression = function named() {};
var fnConstructor = new Function ();

All approaches create a Function object however there are a couple of differences under the hood. Lets take a peek…

1. Function Declaration

The function declaration pattern is one of the most common patterns.


function fn () {
    //function body
}

Once a function is defined using the declaration format; it can be used anywhere in the enclosing scope even before the function body. Confusing? It’s all about hoisting.

2. Function Expressions

Functions are first class objects in JavaScript, thus it is possible to have expressions that evaluate to function values; such expressions are appropriately termed function expressions.

Creating a function expression is easy: just declare a function where the parser expects an expression and it automatically becomes a function expression. This includes assignments to variables and/or object properties, placing functions between parentheses (the grouping operator can only contain expressions),or after a unary operator (e.g. !, +, – etc).

//anonymous function expressions
var fnExpr = function () {};

(function fnExpr2() {} );

!function fnExpr3() {}

Function expressions can be named or anonymous; named function expressions (NFE) expose a function name that is available inside the function body but not outside it. See the snippet below:

var namedFuncExpression = function named() {
    return named.name;
};

named();
//ReferenceError, named is not defined

namedFuncExpression();
//returns "named"

NFEs help to make debugging nicer (we all know how frustrating it is to keep seeing ‘anonymous’ functions in the debugger). It might also come in handy when you need to retrieve a function name by calling toString() or make recursive functions (although the variable name will also serve the same purpose).

Function expressions are essential to achieve functional programming concepts like currying, partials in JavaScript.

3. Function Constructor

The last way is to use the function constructor, this constructs a function object and returns it.

There are a few things to note while using this approach: created functions can only access variables in the global scope or in their own scope and it is no possible to create closures. Moreover, the use of the function constructor is slower since the function body has to be parsed every time it is called. And there are potential risks from malicious agents.

var add = new Function('a','b', 'return a + b');

add(1,2);
//3

var glbFoo = "global";
function scope() {
  var scpFoo = "scoped",
   scop=Function('console.log(typeof scpFoo)'),
   glob=Function('console.log(typeof glbFoo)');

   scop();
   glob();
}

scope();
//logs undefined
//logs string

The parameters to the function are passed in first and then the function body (as a string) is passed in as the last parameter and viola! the function object is returned. The new keyword is optional; it still works without the new.

4. Function expression vs Function declaration

Function declarations and their bodies get hoisted to the top of the scope (no matter where they appear – top, bottom or middle) and are thus available through the scope. However for function expressions, the variable declaration is hoisted while the assignment to the function body only happens at runtime. See the example below:

declared();
//logs declared
function declared () {
    console.log('declared');
}

expressed();
//logs TypeError: undefined is not a function

var expressed = function () {
    console.log('expressed ');
}
expressed();
//logs expressed

5. Spot the difference? Identifying function expressions and declarations in code

Differentiating between function expressions and declarations can be tricky. According to the ECMAscript specification, function declarations must have an identifier, thus if functions without identifiers are unequivocally function expressions. So how do we distinguish between a function declaration and a named function expression?

Function declarations are only allowed as sourceElements of scripts or functions. They cannot appear in nested blocks because blocks are  only allowed to contain statements and not sourceElements. Expressions on the other hand are expressions… :)

//source element examples
var a = 0;
function b () {};
if (false) {
    //nested, not source element
    var c = 0;
    function d () {};
}

//function declaration
function foo() {
    //another declaration
    function bar() {};

    if(true) {
        //function expression because
        //it is not a source element
        function baz() {};
    }

    //function expression
    //expressions expected after unary operator
    !function bng () {};
};

6. Finally…

Still reading? Here are some more examples of queer ways to create functions. Don’t do this at home/work/live/staging/etc.

var f = function (str) {
    alert(str);
};
eval('f("eval")');
//alerts eval

setTimeout('f("timeout")',1000);
//alerts timeout after a sec
};

Remember, don’t do this on live servers…

Did you enjoy this post? Here are a couple more interesting posts:

1. The JavaScript Function
2. Three Important JavaScript Concepts
3. A peek into JavaScript’s Array.prototype.map and jQuery.map

Update

Brilliant explanation of the difference between function and Function by Peter van der Zee:

“The `Function` is a global object and a function value, which generates a new function when called. You create new local variables named `Function` but not with `function` “

Standard
JavaScript, Languages, Learning, Miscellaneous

Three Important JavaScript Concepts


Statements and Expressions

The MDN documentation defines JavaScript expressions as any valid unit of code that resolves to a value.

a = 1;
3 + 4;

The first expression has value 1 which is then assigned to variable a while the second has value 7 which is not assigned to anything.

Since expressions evaluate to values (numbers, strings, functions etc), they can be substituted anywhere these values are expected. Programmers just have to ensure expressions resolve to expected values because of JavaScript’s weak typing.

Consider the following simple statement:

var x = "statement";

This is a statement and not an expression. Statements do something while expressions evaluate to values.

Dr. Axel has an excellent post which differentiates both: “you can use expressions where statements are expected (these are called expression statements) however you cannot use a statement where an expression (i.e. something that evaluates to a value) is expected”.

To simplify; you cannot use the statement above as a condition for an if branch (which expects an expression or value).

Variable Scope

Scope determines the lifetime of variables and where they can be used. Most programming languages have block scope, i.e. variables only exist within enclosing blocks (usually delimited by braces). However, JavaScript has other ideas… Check the code snippet below.

function JSBlockScope() {
    var noBlockScope = "BlockScope";
    if(true) {
        var noBlockScope = "FuncScope";
    }
    console.log(noBlockScope);
};

JSBlockScope();
//logs FuncScope

The output is “FuncScope”! Surprised? Block scope implies that declarations inside blocks do not overwrite external variables. JavaScript has function scope and consequently noBlockScope gets overwritten to ‘FuncScope’.

Function scope also means that variables declared inside functions are only available inside those functions, once the function exits, the variables are inaccessible anymore (well, unless you use closures…).

function scopeCheck() {
    var functionScope = "inside Func";
    console.log(functionScope);
};

scopeCheck();
//logs inside Func

console.log(functionScope);
//ReferenceError: functionScope is
// not defined

The functionScope variable defined inside the scopeCheck function only exists inside the body of the function.

Variables are first looked up in the current scope (i.e. the enclosing function), if not found, then the interpreter continues walking up enclosing scopes until it gets to the global scope. If the variable is not defined still; then the well-known “ReferenceError: variable is not defined” error occurs.

Hoisting

JavaScript has this weird but fascinating concept called hoisting. All variable declarations are hoisted – every variable gets declared immediately even though their values might not be set immediately.

function hoisting() {
    console.log(hoistedVar);
    var hoistedVar = "hoisted!";
    console.log(hoistedVar);
}

hoisting();
//logs undefined
//hoisted!

Explanation

Confused? Well what happens is that all declarations are hoisted to the top before any code execution begins. The above code is totally similar to the one below:

function hoisting() {
    var hoistedVar; //undefined
    console.log(hoistedVar);
    hoistedVar = "hoisted!";
    console.log(hoistedVar);
}

hoisting();
//logs undefined
//logs hoisted!

The log statements show ‘undefined’ since this is the default value for uninitialized JavaScript variables. If they weren’t hoisted, the interpreter would have thrown a ReferenceError. 

Hoisting also applies to functions (JavaScript functions are values afterall…) however there is a subtle difference between function declarations and expressions. Function declarations get hoisted to the top and are immediately available within the scope while function expressions are only declared and not hoisted (much like the same case for variables above). 

function isFunc(fn) {
    var isFn = (typeof fn === 'function');
    console.log(isFn);
}

function isUndef(fn) {
    var ntDef = (typeof fn === 'undefined');
    console.log(ntDef);
}

function funcHoisting() {
    isUndef(declaredFn); //false
    isUndef(hoistedFn);  //true

    function declaredFn () {};
    var hoistedFn = function () {};

    isFunc(declaredFn); //true
    isFunc(hoistedFn);  //true
}

funcHoisting();

Declaring variables at the top of functions helps to avoid hoisting surprises.

Conclusion

I was going to write about function expressions vs declarations, however I believe these three JavaScript concepts would significantly make it easier to understand that topic. Insha Allaah I’ll publish the function expression vs declaration post next.

Meanwhile, here are some other posts you might like:

1. The JavaScript Function
2. A peek into JavaScript’s Array.prototype.map and jQuery.map
3. Programming Language Type Systems I

Standard