Tuesday, December 15, 2015

Caution JavaScript Ahead - Functions as Values

We have seen about the need for learning Javascript ahead in one of the previous post. Is the development in Javascript easy? Absolutely not. Lets see one simple scenario in this post along with other scenarios posted earlier.

http://joymonscode.blogspot.com/2015/08/multiple-ways-to-iterate-array-in.html

Functions everywhere ie Functional Javascript

Javascript runs on key value pair mechanism. Even functions can be added to as value to a key. Since everything runs based on key value pairs and we can change the value of a key at any time including run-time, the environment gets really dynamic.

Look at the below code.

var mathLib = {};
mathLib.Add = function (n1, n2) {
    return n1 + n2;
};

We can see that when the object was created it has no function named Add. We added it later. Calling the function as below will give is the sum of 2 numbers passed into it.

var sum = mathLib.Add(2, 3);
return alert(sum); //Displays 5

This works great. But think about a big project where 100 developers are working on. Anybody can write code to change the value of Add key / property of mathLib as follows. This can even happen after the real Add function is added. Lets consider the below click event handler

function alter_mathLibAdd_Click() {
    mathLib.Add = function (n1, n2) {
        return n1 * n2
    };
}

The above is absolutely valid in js and it will change the meaning of earlier add function. Now think about your code calling the add method.

var sum = mathLib.Add(2, 3);
return alert(sum);//Displays 6

Really!. Yes this is just an example. These kind of things can happen at any time in our Javascript code, if we don't take development seriously. That being said don't just jump into Javascript without proper understanding. It was kind of OK if we jump into Java or C# without much preparation because language + compiler has so many things to get a low quality developer moving.

The property is kind of called Homoiconicity of language in theory. Real homoiconicity means the program syntax and data structure are same. But here its more to program as data.

http://jsfiddle.net/joygeorgek/Lwqnpqvx/1/

Welcome to the dynamic world of Javascript.

1 comment:

Blogger said...

Get all the best spirits and wines at Duty Free Depot!

All the world famous brand name drinks for unbeatable discounted price tags.