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 () {

//Another style
(function () {

//passing in variables
(function ($) {
    console.log('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() {

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() {

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 () {

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

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() {

//ReferenceError, named is not defined

//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');


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


//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:

//logs declared
function declared () {

//logs TypeError: undefined is not a function

var expressed = function () {
    console.log('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) {
//alerts eval

//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 and


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` “

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";

//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";

//logs inside Func

//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.


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() {
    var hoistedVar = "hoisted!";

//logs undefined


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
    hoistedVar = "hoisted!";

//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');

function isUndef(fn) {
    var ntDef = (typeof fn === 'undefined');

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

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

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


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


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 and
3. Programming Language Type Systems I

JavaScript, Languages

The JavaScript Function

JavaScript is a functional programming language and it is essential to truly understand functions to achieve mastery of the language. In JavaScript, functions are pretty much at the same level as objects: you can assign functions to variables, access function properties, pass them in as parameters to other functions or invoke them using the function operator.

Functions and their Names

Like many other languages, JavaScript supports named and anonymous functions. Well, named functions have names and anonymous functions are anonymous :) . So how would you know an anonymous function?

function namedFunc () {};


//logs "namedFunc"

Unless you assign a reference to an anonymous function on creation, it will be impossible to reach afterwards. The common var func = function () {} pattern is the workaround for this; note that the variable is not the function – it is only a reference to the location of the anonymous function.

var anonymousFunc = function () {};


//Empty String

Aaaah… assigning an anonymous function to a variable does not a named Function make. :)

Function Referencing

You can assign named and anonymous functions to variables, you are simply getting a reference to the function.

var known = function knownFunc() {};



And then it gets even more interesting… The handles are just pointers to memory locations and it is possible to reassign them as you wish.

var initialRef = function () {

    console.log("Initial handle");


var laterRef = initialRef;

initialRef = function () {

    console.log("New handle");




So what do you think the initialRef and laterRef calls print out? “New Handle”? Well I thought so too but the output is surprising:


//logs New handle


// logs Initial handle

References are just pointers to function memory locations; if one reference is re-assigned,  the other references continue to point to the initial memory location. It makes no difference if you use named functions too: you cannot edit a function once it has been created, you can only change its reference.

Function names are readonly

Just so you know, the name property of functions is read only and does not throw an error if you write to it. Aside, this feature is not available on IE.

function readOnlyName () {}; = "Changed";


//logs readOnlyName

The function invocation expression

The JS function operator is the () and it allows you to invoke any function expressions. Anonymous functions are invoked by appending () to their references (as shown in examples above).

This means that any function expression can be invoked using the () call, it just necessarily have to be an explicit function declaration or function reference. While this might sound trivial, this is the feature that makes Immediately Invoked function expressions (IIFEs) possible.

I do hope you’ve learnt something new about the JS function; upcoming posts will insha Allaah cover more about JS functions (things like IIFEs, function scope and forward referencing aka hoisting).

Did you enjoy this post? Check out some of my other articles

1. Static and Instance Methods in JavaScript
2. A peek into JavaScript’s and
3. Programming Language Type Systems II
4. Design Patterns: PubSub Explained

C, Computer Science, Java, JavaScript, Languages, PHP, Programming Languages, Python

Programming Language Type Systems II

Strong/weak typing describes the ease of mixing variables of different types in expressions. Strong typing does not imply static typing just as weak typing does not mean dynamic typing.

To put it simply, if a programming language tries to interpret an expression containing variables of varying types at runtime (e.g. adding an int to a string), then it is most probably weakly-typed however if it throws an error; then it is strongly-typed.

Strong Typing

Strongly-typed languages do not try to deduce programmer intent when they come across expressions containing varying types; they throw errors and do not do any implicit type coercion.

two = "2"; #String

four = two + 2; #KA-BOOM!!!

#TypeError: cannot concatenate
'str' and 'int' objects

This should not be confused with dynamic typing where a variable’s type can change; the issue here is trying to use a type (string) where another type (int) is expected.  To make the above example pass, the string needs to be cast into an int.

two = "2"; #String

four = int(two) + 2;

#four is now 4

Weak Typing

Weakly-typed languages allow you to mix types in expressions: the compiler will not throw an error, rather it’ll try to deduce your intentions. This can lead to really weird bugs that occur one thousand miles away from the origin.

var four = "4";

var five = four + 1;

console.log(five);//prints "41"

The compiler implicitly assumed that you were concatenating strings (the expression is ambiguous: it involves adding a String to a Number) and ‘helped’ to make this happen. However, the code will probably blow up because five is not 5.

What you should know

Strongly-typed languages do type-checking on variables at runtime and only allow legal operations for that variable type to be carried out whereas weakly-typed languages try to inteprete (understand/guess) the user intentions.

Strong typing does not imply static typing, it means that a language will not automatically coerce a variable into another type to make expressions valid. Weak typing however means that the type of a variable can be changed at run time based on its context in expressions.

In general, the ease of detecting programming errors decreases as you go from one to four in the list below. Due to the implicit conversions in dynamic weakly-typed languages, bugs might be caused by seemingly innocent code.

1. Static & strongly-typed: Haskell

2. Static & weakly-typed: C

3. Dynamic & strongly-typed: Ruby, Python

4. Dynamic & weakly-typed: PHP, JavaScript

And Finally…

In conclusion, it is good to know that  the strong/weak delineation however is blurred and not clearly-cut. To avoid ambiguity and confusion, it’s better to describe languages with respect to type safety and that should insha Allaah be the next post in this series. Hang on…

Did you enjoy this post? Read the first post.

Computer Science, Languages, Programming Languages

Programming Language Type Systems I

Static, dynamic, strongly-typed and/or weakly-typed; the terms we routinely use to describe typing in programming languages. However, these terms (especially the last two) have more to them than is generally assumed.

There is actually no widely-agreed upon definition for strong and weak typing – there are way too many contradictory views. Good news is that everyone agrees on dynamic and static typing, so that’s first.

Static typing

In a statically-typed language (e.g. Java, C#), type information is bound to the variable and checked at compile time. For example,

    String staticVariable = "static";
    staticVariable = 1; //BLOWS UP

The type of variable staticVariable will always be String, it can never be an Integer or Double. It might eventually be reassigned to a different string or even point to null but its type is NEVER going to change.

Dynamic typing

In a dynamically typed language (e.g. PHP, JavaScript), the type of a variable is bound to its value and type checking occurs at run time. This makes it possible to do things shown in the example below:

//Starts out as a string
var dynamicVariable = “string”;

dynamicVariable = 2; //Now an integer

dynamicVariable = [1,2,3]; //Now an array

dynamicVariable = {}; //Now an object

So which Typing class is better?

Please no language wars; both typing categories (static and dynamic) have their strengths and weaknesses.

With static languages, all operations are checked by the compiler, variables convey type information and compilation exposes bugs early. However, they are usually more verbose and it might be difficult to succinctly write versatile functions which accept multiple parameter types.

Dynamic languages are generally slower than static languages because methods and types have to be looked up and evaluated at run time. However, their low learning curves, flexibility and malleability make them perfect for quick prototyping.

Summary (tl;dr)

1. There is no universally-accepted definition for strong or weakly typed languages. (c’mon, computer scientists can surely do better huh?).

2. The static/dynamic delineation is completely independent of the strongly/weakly typed category, they are disjoint sets.

Insha Allaah my next post will be on Strong vs Weak typing; some explanation of the issues and why you should not use it too often in describing languages.

Life, Miscellaneous, Musings

Maximizing Value: Learning to do less

I have always been concerned with maximizing efficiency for a long time; before, it meant learning everything I could in the shortest time possible. To me then, ‘done’ meant completing a book or series of videos and this blinded me from verifying acquired knowledge. So I mostly went from one book to another without challenging myself to find real-life applications.

The trend continued when I began at Masdar: I tried to read all the library books I had longed to read, signed up for a lot of online courses and took on side projects. I soon got burnt out (I was doing too much at once) and quickly learnt to respect my limits.

The unpleasant burnout experiences also made me review my daily schedule: were all the tasks really completed? I started planning my days, used pomodoro time blocks to improve my focus and abandoned multi-tasking. My ‘completion’ speed dropped however Alhamdulilah I started completing stuff consistently without getting burnt out.

There is a long ever-growing list of fascinating things I want to do however I know I can’t do everything. A couple of days back I started to question my activities: how have I applied the stuff I keep learning? What were the results? Have I been doing the right things? Alhamdulilah I can reasonably follow up on tasks consistently now, so the next challenge is to focus on the right things. 

Insha Allaah I hope to improve by aggressively whittling down the fascinating list of to-dos, everything I do should have an impact or align with my goals. Less can actually be more…

Insha Allaah I’ll be asking these four questions:

1. What am I doing?

2. Why am I doing this?

3. Does this align with my purpose?

4. Am I doing it well enough?

Summary (tl;dr)

Know that you can not do everything, know your limits and then do the things you can do excellently. Finally, always remember to pray to Allaah and rely on Him totally as all success is from Him alone.

May Allaah bless all our efforts and grant us all success.