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 and partial application 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. If functions without identifiers are unequivocally function expressions, 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` “


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

The Art of Debugging

I recently wasted a lot of time while attempting to use the amazing Dropzonejs image uploader. I left out a function call in an overloaded function and this broke every subsequent call. More annoyingly, I could not pinpoint the cause of the error as Dropzone was failing silently.

Close to giving up, I decided to give it one more attempt and went to my sandbox – I create a safe area in all my projects for doing ‘risky’ stuff. Starting afresh there, I was amazed to see that everything worked fine. A close comparison of the code samples revealed the bug’s origin – the left out function call. I double-checked to confirm this and that was all about it. Sadly, the documentation does not mention that a failure to call done() in the accept function will break the code silently.

Programmers usually spend a lot of time debugging and it can be a painful experience;  some feel like tearing out their hair in exasperation, smashing their poor computers or even believing that their computers really ‘hate’ them! :)

Actually computers do not hate people and the operating system is not conjuring bugs – the most likely reason is buggy code. Here are a couple of tips on debugging; hopefully these will help to reduce time spent, frustration and annoyance levels.

The Inefficient Way of Debugging: Trial-by-Error

Random guesses? Print statements littered around? Fast fixes that ‘appear’ to work? Do these ring a bell? Welcome to the bad bad way of debugging.

This approach is fraught with a gazillion issues. The worst being the potential introduction of new bugs into the codebase. Lucky bug discoveries offer little learning opportunities and it might be difficult to reuse knowledge gained from such fixes in the future.  Also, such run-of-the-mill fixes tend to be inelegant and stand out like a sore thumb when compared to earlier designs and architecture.

The Efficient Ways of Debugging

1. The very first thing is to create a list of the likely causes of the bug; this usually involves thinking deeply about loopholes and design flaws. Studying program error dumps and buggy behaviour might also help.

2. Go through the list while eliminating disproved hypotheses. Once a likely cause is found, a verification needs to be carried out; this can be as simple as proving that the bug appears only when that cause is activated.

3. Don’t just rush to write a fix – I bet you would not want your ‘super-fix’ to mutate into a monster ‘bug’. Think deeply about the bug and what potential ripple effects a fix could have. Also think about how the proposed fix would work, how it blends into the system’s architecture and possible design impacts.

4. Yes, you got it!! Go ahead and squash that bug! Yuck – I dislike bugs.

5. Not finished yet, you need to go through your code armed with your newly acquired bug-terminating powers. Find and ruthlessly sanitize code likely to suffer from such bugs. Rinse and repeat – always leave code in a cleaner state than before.

Extreme Approaches: When the Efficient Ways Fail

You might apply all the above and still be stuck in a rut; this might occur if you have extra-terrestrial bugs (quite popular in multi-threaded environments).

6. Total examination

The brute force approach is bound to work insha Allaah although it involves painstaking work. You go through the code thoroughly (a debugger should come in handy); this might involve examining all execution paths if possible and trying to pinpoint the issue. Hard work…

7. Start afresh

When everything fails, why not throw out the old code and write it again?

Some other tips

6. Very important, set a time limit

Do not spend 3 days hours trying to fix a bug if you can re-implement the same feature in 2 hours. If you are sure you can rewrite a bug-free version of some buggy code, go ahead with a rewrite and spare yourself the trouble. Time counts.

7 Learn to use tools

Debuggers, memory examination tools and profilers. They will help point out to what might be causing the issue. I once had a really really nasty bug while using jQueryUI, the bug only showed up on a particular browser and only when the page was accessed over the local network; otherwise all was fine.

I eventually had to use a profiler after several failed debugging attempts, I  then discovered that a function was being called several hundred times. Bug case solved!

8. Discuss with a buddy

Find a programmer / buddy to discuss with, discussing your ideas with someone will help you to find design gaps and flawed assumptions; you might be surprised that you get the error spot on without any contribution from your buddy.

Now go ahead and eliminate some bugs :).

The Myth of Perfect Software

Programs do not acquire bugs as people acquire germs, by hanging around other buggy programs. Programmers must insert them… Harlan Mills

Software breaks all the time: booting issues, corrupt software and files, crashes etc; nearly everyone has had a close shave or two with fragile software. Can programmers write ‘perfect’ fault-free software? I presume a trip to Uranus would be much easier, here I come NASA! :D.

A program’s complexity scope is way too large to fit in a programmer’s mind. It is difficult (nigh impossible) to ascertain a program is valid, in fact it is extremely difficult to know the number of errors in software. Here is a simple example, exhaustive validation of an 8 character field would require checking 26^8 combinations (assuming only letters a-z are allowed). Real-life programs contain typically have larger problem domains.

Since achieving a utopia of bug-free software is not feasible, we might as well set our sights on something much more achievable – producing robust software. Robust code doesn’t translate into perfect software; however it tries to behave ‘nicely’ when things go awry – i.e. it does not wipe your hard drive.

Here are a couple of suggestions for writing robust code:

1. Don’t trust anything that comes in from external sources – sanitize, validate and then confirm. You can also log suspicious activity and have default fallback actions.

2. Remember Murphy’s law (“Anything that can go wrong, will go wrong”); that 1 in a 10000000000000000000000000000 chance event needs to be handled even if you ‘think’ it’ll never happen. This is software + humans, remember the large complexity space?

3. It is essential to write simple, flexible, extensible code; if changing one parameter breaks the source then you need to refactor. Also keep in mind the YAGNI principle and do not write unnecessary code just because you feel like it.

5. Write the least amount of (clear) code needed – The less code you have, the less the complexity (and the number of likely bugs/errors) and the better for everyone.

6. Keep cyclomatic complexity low, the fewer the number of executable paths in your program the simpler it is.

7. Test your code and when ‘bad’ things happen, remember to exit gracefully.

Do try to write robust code; you’ll save yourself future worries, impress your customers (which likely translates into lots more $$$ from future referrals) and improve your craft.

This post was motivated by my fascination with the ext file system…. I keep having boot issues with my Ubuntu installation whenever I force it to shut down – this causes the ext file journal system to end up in an unclean state. While in this state, the operating system does not load and I keep ending up at the initramfs prompt. A live disk, some tweaking at the terminal (e2fsck) and the operating system is good as new again.

Grunting with GruntJS

I have been working on a team using a diverse tech stack: PHP, MongoDB, EmberJS and requireJS. Since we intend to release the alpha version in a few weeks insha Allaah, I had to bring everything up to production-ready levels. The usual needs: Javascript linting and obfuscation, resource (JS, CSS + images) minification, test automation (unit + functional) and a few others.

One thing I like about the project is that it gives us a chance to explore and try on new technologies – the best way to learn something is to implement in it. From EmberJS for MVC JavaScript to requireJS for AMD (helps to maintain code sanity) and now GruntJS for automation (I have been yearning to try out Grunt for looooooooooooooong).

GruntJS was written by Ben Alman, same guy who wrote tinypubsub. He wrote it because found it difficult to set up his loads of projects easily. It is in the same category of tools like make, maven, ant and rake. Unlike these tools, Grunt is refreshing and a cinch to grasp – the simple ‘JavaScript-y’ approach got me sold. Also, there are an immense number of 3rd-party add-ons that send give programming bliss; I agree it might not be as flexible as other tools (can you grunt Java? Doubt it) but it does what it needs to do and does it well. That’s all I need for now…

My team’s current Gruntfile config includes options for linting, minification, obfuscation, SASS compilation, live reload, qunit testing for unit testing and also casperjs for functional testing. All tests are run against a phantomjs headless browser.

Lessons? Never take on a side project without learning something new. So what else? Here are a couple of reasons why you should consider GruntJS:

1. Standardized interface – it defines a completely repeatable method for defining tasks.

2. Great community – there are one gazillion plugins, tutorials and blog posts on why you should use Grunt.

3. Plugins for nearly every web dev work you’ll do – I personally love the watch tasks that reload the browsers.

4. The learning curve is almost non-existent; I love easy-to-use stuff.

5. Grunt is powerful – it packs a punch!

6. Flexible, I found out that you can actually invoke command line arguments and run new programs.

Thesis Stories Ep 3: Research is Hard!

Alhamdulilah I completed my thesis about three weeks ago; if you’re interested, you can check out my thesis and presentation. Looking back at the two years I spent at MASDAR, I have a couple of thoughts: Alhamdulilah I learnt a lot, met a couple of wonderful people and matured significantly. There were a couple of not-so-pleasant experiences too but I believe I emerged stronger ultimately.

So I switched to the complexity analysis of road networks after my stack overflow adventure ended unsuccessfully. It was a fresh start but I had no alternative since I wanted to graduate. In the end, I defended all my hard work in about 75 mins – imagine! Nearly 6 months of work translating into just 75 mins!!

Research is difficult! As difficult as any other endeavor; I think most researchers don’t know how their efforts will turn out (as most start-ups do at the beginning too). There is usually some hunch about a model, some experiments and then eventually they have to figure out what the ‘right’ result is. Also, ‘big data’ appears to be fun and cool but it requires unbelievable and prodigious amounts of grunt work.

I built JIZNA, a custom Python framework for complexity analysis. JIZNA can parse openstreetmaps XML dumps of cities (the parser was an open-source utility I found and modified), create dual graphs of these networks, merge discrete roads, exclude outliers and calculate the desired metrics. These metrics were used to predict how difficult it would be to search the city. The JIZNA platform is available here.

The Cool Stuff

I think I wrote much better code: the framework was modular, nicely designed and flexible; I was able to write some really cool algorithms for the complex computations and I learnt how to use Sphinx, the Python documentation tool. Sphinx, in my opinion, is a lovely tool once you grasp its basics.

The Not-so-Cool

I got a couple of interesting results however I think they were not so spectacular. I guess further work would reveal some new insights.

I had to throw away some of my code (a complete simulation framework had to be discarded when the approach changed) and my writing (again! This is the umpteenth time I’d be chopping off my writing).

So what did I learn? Lots more Python, algorithms, software design, documentation, writing, latex, vim and some maths (mostly matrix algebra). However, more importantly, I came to appreciate the value of grit, determination and perseverance while working towards goals. Don’t ever give up, even if all appears to be lost.

Next plans? I don’t quite know fully yet; one thing for sure: research is hard! :)

Did you like this post? Check out my other posts on Grad School.

For Devs only

I try to do less to achieve more – it is good; it makes me do my job faster and more easily; you should do so too. Automate, use shortcuts, innovate; well the initial investment might take a lot of time but it’s something you will be glad you did.

You can learn a lot by just exploring the tools you use daily. Just try to find a simpler way: some previously unknown feature in your favourite IDE, a macro to allow you repeat a series of actions or just something that saves you some keystrokes. So, I decided to post a couple of tips; I do hope you find them cool and pick up one or two new ideas.

Warning: Some of these work on linux only.

1. Bash Shortcuts

I stumbled upon these while going across someone’s .bashrc file and it stuck me as awesome; yes it is plain awesome. For example, accessing my /var/www/my-web-project folder (and I do access it often) is a pain; why do I have to type cd /var/www/my-web-project all the time? Solution? Just add the following shortcut to your .bashrc:

alias myproj=’cd /var/www/my-web-project’

and that’s it; I just type myproj in bash and am routed to that location. And yes, it doesn’t matter what directory I am in.


Bookmarks are cool, I think they are absolutely essential. Now, if you don’t know how to use them or don’t use them in your IDE/Editor; stop reading and find how to use this wondrous time saver. I use bookmarks a lot in vim and Netbeans (and all other editors if possible); this allows me to jump around and move around. Yes, find out how to use bookmarks and use them!

Talking about vim; I think it’s really awesome and allows you to effortlessly edit anything that is text: I use it for code, latex, writing anything everything. At times, it might be easier to use a less powerful editor however most times, it does all and really cool too. And if you’re a ‘vimmer’, then try out these plugins: nerdtree, nerdcommenter, syntastic and latexbox (if you write in latex).

3. Debugger Statement (JavaScript)

I picked up this while watching an EmberJS tutorial and it has become a major part of my arsenal. Maybe I overuse it (well, I have to write so much JavaScript nowadays). Just put a debugger statement in any part of your JavaScript code and fire up that page in your browser; whenever execution gets to that point, it’ll automatically stop. I use this virtually everytime nowadays and for JavaScript devs; it’s a must use. Another cool JS tip involves using the console object; I use console.log too often but there are a couple of other cool functions like console.trace(), console.dir() etc.

4. Picking an object with a particular Characteristic

I picked up this trick while working in Python on my thesis: I often needed to pick up objects with certain properties out of long lists of objects. The interpreter is essential and this is what I do:

for obj in objectList:

if obj.ppty == criteria:



Obj is now equal to my desired object.

5. Testing for -1 (Nice Discovery from SO)

I picked up this explanation from stack overflow and couldn’t help sharing it. I do hope you wouldn’t write code like this but it is always great to gain some insight into how things work.

Assuming you want to test if something is equal to -1; in 2’s complement systems, the representation of -1 is 11111111 (for whatever number of bits the system supports). Just take the bitwise inverse of that number and all you get is zeros. Now for the cool part, zero is a falsy value which can be used in your tests. Here is the link.

Hope you picked up something or the other from this; if you did; do share it with someone who might pick a point or another from it.

Did you like this post? Try out some of my other posts:

Taking the PAIN out of coding

Over the years, I have learnt some tricks and picked up some lessons while writing code. Most were learnt the hard way, so I decided to share a couple of tips on how to avoid development pitfalls.

Meticulous Planning and Design

One of the most difficult lessons I learnt in software development was not to rush into code; I used to jump impulsively into software projects and start hacking away at code without planning fully. And as you can bet, the thrill of coding soon evaporated when I got bogged down by messy code. Sadly, many projects of mine met their nemesis this way.

Now, I am just too lazy or maybe too battle-scared to do that; I mostly write out a high level system design document (usually a single page or two) describing all the major features. Next, I run through everything to know that the various components and interfaces are logically valid and try the edge cases. Only when I am satisfied with this do I start writing code.

Alhamdulilah, I think I write cleaner, more modular and better designed code this way. For example, I recently had to extend an experimental framework I wrote a couple of months back; surprisingly I was able to make all major changes in less than two hours. Better still, nothing broke when I ran the framework again!

A dev lead once told me coding is the easiest part of software development… I think I agree with him…

Do it fast and dirty, then clean up

I started using EmberJS last year for a web project. EmberJS is a really cool framework and reduces the amount of boilerplate code you have to write: it’s so powerful that some things seem magical. However, EmberJS has a really steep learning curve.

As usual, I was trying to write perfect code at my first attempt, did I succeed? Your guess is as good as mine. I got so frustrated that I started hating EmberJS, the project and everything remotely related to the project. :)

Before giving up, I decided to have one more go at it; my new approach involved ignoring all standards and good practices until I got something to work. And that was it, I soon got ‘something’ that looked like a working web application running. One day, while working on the ‘bad’ code, I had an epiphany. In a flash, I suddenly knew what I was doing wrong. Following standards and practices was relatively easy afterwards.

Looking back, I realize that if I was bent on doing it perfectly at the first go I most probably wouldn’t have gotten to this point. Oh by the way, EmberJS got a new release so my code is obsolete again. :P

Clean up the code from step 2 above X more times

This is a part of development I don’t think I really like but it is essential for maintenance. You have to go back through the code (yes, your code; you ain’t gonna make life miserable for the developer inheriting your codebase). Refactor all duplicated, extraneous and obscure pieces of code ruthlessly. Most importantly, improve the readability of the code (yes, readability is REALLY important – make it read like a good novel if possible à la Shakespeare or Dickens).

I also keep a running list of all the hacks I make as I go about writing code in step 2; this list comes in handy at this stage and enables me to go straight to the substandard code pieces and fix them up.

Use a consistent coding style

I recently noticed that my coding style was inconsistent across my projects: variables names were either under_score or camelCase while method declarations used brace-on-new-line and brace-on-same-line approaches.

The problem with this approach is that it breaks up my flow of thought and makes speed-reading code difficult. Now, I choose a single style and stick to it throughout a project – any style is fine provided I use it consistently.

Scientific Debugging

I came across the term ‘scientific debugging’ while blog-hopping and it has stuck in my subconsciousness ever since. Identifying bugs can be a challenge: for small projects, I just try to figure out where the bug might be and then check for this. However, this approach does not scale, I wouldn’t randomly guess on a 5000 line project.

Scientific debugging is a systematic process: you make hypotheses about the likely causes of the bug, make a list of places to check and then go through this systematically while eliminating entries. You’ll most probably find the bug with less effort and without running through the entire list.

Project Management

I rarely used to track how much time and effort I put into my projects; I would just code and code and code. Now I know better, I estimate how many hours I can put in before, during and after each project. I try to use Agile (although, I use a simple list + pomodoro too) for project planning, task management and effort estimation. It is now trivial looking up my project status: implemented features, issues list and proposed features.


I tried my hands at TDD last year and I felt it was just a way of doing too much work for coding. While I might be wrong about TDD, I think it’s essential to have a solid testing process in whatever project you’re doing.

Test, test and test: run the gamut (if possible): unit, integration, functional, stress, regression etc.

Enough said… I have dirty code to polish. If you did find some of the points useful, please share your thoughts and ideas.

Related Posts

  1. Symptoms of Software Rot
  2. So you want to become a better Programmer
  3. Clean code, Dirty code

The language Series: Python

My Python Story

I had always wanted to learn Python ever since I was an undergraduate but my commitments took all my time. Alhamdulilah, I finally got my chance in my first semester at MASDAR when I had to do the Artificial Intelligence project in Python. It was a pretty challenging one; it involved building a framework that used brute-force in solving problems with humongous search spaces.

It has been a nifty tool for my research work too: starting with stackoverflow to openstreetmap data. Python provides easy-to-use tools for data cleaning, processing and graphing; some of its libraries are a sheer pleasure to use: matplotlib, networkx, scipy, numpy etc. More importantly, I can write my full processing stack in Python without having to resort to other languages or tools. Although, there are speed and memory consumption trade-offs; overall, it’s been a pretty good bargain.

The Good Parts

  • The language has an almost non-existent learning curve; it’s soooooo easy to learn.
  • Comes in handy when you want to write a script or solve a little problem.
  • An awesome community, nice package management and great libraries – examples include scientific libs (matplotlib, numpy, scipy) SQLAlchemy, PyTables, Sage, networkx.
  • Cross-platform and supports full-stack development.
  • Great readability, high expressiveness and a very simple grammar – almost reads like English at times.
  • Allows returning multiple values from a method.
  • Some cool supported operations in Python:
    • Swapping: x, y = y, x
    • Floor division: 5.0//2 = 2.
    • Comparisons: if 3 > x > 1: print x; I don’t know of any other language that has this feature.
    • Iterating through two lists simultaneously using the zip keyword.
    • List comprehensions are super-awesome.

The Bad Parts

  • Speed; Python is slow :(.
  • Memory consumption; you can’t explicitly free memory and it’s not suited for situations requiring extremely small memory footprints.
  • Inadvertent overwriting of default functions or settings. For example, I once did this str = “blah blah blah”; Python raised no objections, it meekly overwrote the str() function.
  • Multi-threading support is not too good.
  • Scoping issues: variables fall out of scope so it’s essential to choose unique names.
  • .3/.1 = 2.99999999999999996. The floating point issue rears its ugly head again.
  • Constants… Python does not support constant declarations out of the box; seems JavaScript got friends.

The Other Parts

  • The indentation can be a pain if your editor gets it all messed up. Use a good editor (vim/Emacs) and make sure your tabs are converted to 4 spaces.
  • IDE support ain’t that great since it’s a dynamic language and there are lots of ways to do the same thing.
  • Weird syntax for the ternary operator : True if condition else False
  • Installing libraries can be a really painful operation if you get it all wrong.
  • Since it’s not a statically typed language, typos aren’t detected until your program goes KABOOM!
  • How do you declare private variables in classes? I still don’t know.
  • Explicit addition of self all the time; I think it is needed to know the current execution scope but still….
  • There is no switch statement in the language; workarounds exist though.

Beginning Python?

Do it! Just jump into the language, learn the pythonic way and slowly you’ll come to see its beauty. It might feel weird if you come from a ‘braceful‘ language (i.e. Java et. al. ) and some concepts might initially perplex you. However, once you get used to the language, I bet you’ll wonder how you managed to get stuff done in other languages.

The sheer expressiveness is amazing at times: you write so little and achieve so much. I think it’s fantastic for data processing, little scripts and heavy lifting ( provided you have enough memory and processing power; some libraries allow you to leverage highly optimized C/FORTRAN code so it’s not totally bad).

Also learn to use the interpreter (you can also try ipython if you’re just starting out) – I use it a lot to speed up my development process and for debugging.


8.5 / 10

One of the easiest languages to learn and use for scripting needs and comes in handy for  rapid prototyping. Extra bonuses include loads of great libraries, support for OOP and functional programming. Sure, it has a few issues but what language is perfect?

Python will probably make you lazy but why do more if you can get the same results with less? :)

Did you enjoy this post? Check out my reviews of C, Java, PHP and JavaScript too.

UPDATE: Thanks to a reader for clarifying my wrong assumption about Python’s ternary operation support.

The language series: JavaScript

I was pretty much amazed to see a JavaScript library for Arduino last year; it’s common knowledge that the language powers uncountable web sites, mobile applications and even Windows 8 apps, but Arduino? Mind-blowing. The ever-growing need for powerful web experiences propels the adoption and development of this remarkable language. 

JavaScript was influenced by C (syntax), Java (naming conventions), Scheme (functional programming and lambdas) and Self (Prototypical inheritance). The rushed development and deployment of the language explains some of the flaws in the language;  however, it exposes a powerful and beautiful core once you know it well enough to fully leverage the benefits of prototypical inheritance (good for programmers to know), functional programming and its unique development idioms.

My JavaScript Story

I started learning JavaScript in 2011 after copy-pasting a gazillion snippets off the internet (yes, I was guilty of that).  My first read was jqfundamentals and then eloquent JavaScript; both are excellent books by the way. However, I learnt nearly all the JavaScript I now build on during a 12-week internship; it was an awesome but sometimes grueling experience – I had to read Douglas Crockford’s book, dig into jQuery and follow first-rate dev methods and practices.

The bad parts

  • What is this? (Pun intended). It can refer to the window object or the object instance it was called on. Be careful with this. :D
  • Addition and subtraction can be string concatenation or mathematical operations. See below for examples.
  • The == and != operators carry out implicit type coercion, you have to use the === and !== operators which check for type and value instead.
  • The evil eval has led to security issues, avoid it totally. A few good uses exist though but you should still avoid it.
  • The parser automatically inserts semi-colons after statements; leads to weird bugs. Make sure you add semi-colons where they should be.
  • Global variables, you forgot to declare some variable properly? No problem, JavaScript stuffs it in the global object. Good luck finding these.
  • Inconsistencies in browser support.

The Good parts

  • First-class functions and lambdas; whoot!
  • Prototypical inheritance; a powerful object model as objects are not limited to being instances of a single class.
  • Loose typing boosts expressiveness and ease of use.
  • Cross-platform and widely-used; in fact you’re using JavaScript now.
  • The good subset of the language is really beautiful and powerful.
  • Closures are pretty cool.
  • Lots of support, there seems to be a never-ending stream of new fancy libraries, frameworks and utilities.

Weird JavaScript

Now some of these are truly incredible; if you don’t believe me, fire up the console in your browser and type them in!

  • ‘5’ + 3 = ’53’ while ‘5’ – 3 = 2.
  • “” == 0 and 0 == “0” evaluate to true but “0” == “” is false, shouldn’t equality be transitive?
  • 0.1 + 0.2 !== 0.3; in my browser, the result is 0.30000000000000004; however I really don’t trust floating point operations anyway as computers have issues with them. Best thing is to always to use some epsilon value as a buffer range.
  • typeof([]) === typeof({}) === typeof(null) === “object”.
  • [] + {} = “[object Object]” but {} + [] = 0!
  • NaN !== NaN

How Most People learn JavaScript

A lot of people get into JavaScript by copying useful code chunks on the internet and plunking them into their codebases (I still haven’t met anyone who explicitly chose to learn JavaScript). Afterwards, they need more control and expressive power so they decide to integrate and leverage a library (most probably jQuery). Ultimately, most people find themselves learning more about their preferred library.

Next, they go ahead to learn the language itself by reading a couple of books about it and attending conferences. The JS enlightenment comes handy in understanding the quirky behaviour of the language and makes it easy to use huge big frameworks and libraries (e.g EmberJS, backbone, etc). In the long run, motivated programmers eventually start writing their own plugins and frameworks.


Great tools like JSHint and JSLint help spot potential pitfalls and save you from tearing out all your hair in frustration, agony and annoyance. They also reduce the chance that there’ll be some irate developer in the future looking for ways to hurt you or cursing you every single day.



An easy language to use – most programmers actually started out by copying code snippets without fully understanding the language and slowly grew to learn it. It runs on the client side, server-side and there are wrappers for most devices. JavaScript is a dynamic prototypical loosely typed functional programming language with some ‘swagger‘ at its core.

Did you enjoy this post? Check out my earlier posts on C, PythonJava and PHP.