Skip to main content

The wierd yet awesome world of Javascript!!

Hey,

Back, again!!

This time we will talk about some weird things which only happen in JavaScript.

When I say weird, it means that if you come from a C++ or PHP or JAVA background it will be hard for you to digest that many concepts that we learned for those languages, and then think will apply in all the majority of programming languages out there, don't anymore apply here in JavaScript.

A very classical and highly cited example is Objects and Inheritance without Classes, well I never imagined this could be done, but JavaScript does it, that too elegantly.

Probably you are already aware that for Class JavaScript uses function(){} and not the conventional OOP Class.
Well actually it uses or rather can use function for multiple other uses as well.
Lets go through some of the amazing features of JavaScript.

Loosely Typed

Try this for a function in your browser console -
If you look carefully here, func is a variable(in the way it is defined) which is used as a function, so basically its a variable of type function which can easily seen here Isn't it weird!! So basically you could say that JavaScript is the one of the most loosely typed language you could come across; think about it, which programming language will let you do this.

Pass by Value or Pass by Reference

Think about the following code in PHP

Works fine as expected.

But lets try a similar code in JavaScript

Its so weird, isn’t it?? So what just happened here?
You see, in JavaScript, when copying variables, which are objects, arrays and functions, and not the simple types like number, string etc, both the variables point to the same object(the original item), as explained by Mozilla JavaScript reference here.

Well its actually in a way similar to PHP, as in, this is exactly how PHP behaves when dealing with Objects. In PHP the object would reference to a pointer, and if copied, the new object will again reference to the same pointer, check here

Similarly in JavaScript while creating an Object(the standard built-in type) or Array, an instance of the type Object or Array is created, and when its an instance, the variable referring to it will always have its reference pointer as the value. And because it has the pointer as the value, only the pointer will be copied(called copy-by-reference) in the new variable and thus it will always refer to the same object.
Try the following in your console. 
Array instanceof Object //true
Object instanceof Array //false
This means that in Javascript Array is a type of Object, that's why the behaviour.

So if this way of copying doesn't work, then how to copy objects?

Here is where libraries like jQuery, lodash, angular have the copy functions, which actually iterate through each and every internal variable and copy its value and index into the new variable, something like the following.
Its because of this copy-by-reference, that when comparing two distinct arrays or two distinct objects, it will always return false, as the reference is compared in these cases and not the actual values.

Objects, Inheritance and Closures

Now as we already know that JavaScript does not provide conventional Class way of OOP, then how does it do inheritance? Does it really do it?
Instead of implementing the Classical Inheritance, JavaScript implements Prototype Inheritance.

All right, we just used some huge words here, lets see what they actually mean. Check the following code with function acting as a class(and basically its constructor) and lets try to understand it. You see, weird again!! Probably the following will make it clearer to understand.
  1. JavaScript does not make distinction on function declaration. A declared function can be used as a Constructor or a normal function.
  2. But if the user wants to use it as a constructor, it has to be used with the new keyword.
  3. Of course we need to use the this keyword bind the internal data with the Object.
  4. And because every variable type in JavaScript has its prototype which is cloned to create its object(or instance). In case of functions the prototype is an object(the instanceof check returns true in the above mentioned example), and we just need the new keyword to make the function act like a constructor of that prototype
  5. In fact, the prototype can still be accessed from the newly created object, via obj.__proto__
For further details, exactly quoting Mozilla's JavaScript Developer guide on this -
  • A new object is created, inheriting from foo.prototype.
  • The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
  • The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

Some more on Objects, and what is Closure after all?

Lets move a little deeper in Object Oriented programming in JavaScript. And take a simple case where we want a function to access the Private properties of an object.
To achieve this behaviour in JavaScript, we need to use something called Closure. And this is how we could use a closure -
So what is a Closure and what exactly it does?
Well, to put it in simple words, Closure is a method of function implementation in JavaScript, which keeps a copy of all the local variables against the created Object. Quoting MDN -
the function defined in the closure 'remembers' the environment in which it was created
So as we can see in the mentioned example that the "constructor" argument arg_one and a "private property" count are available to the only their respective object at all the times, and every subsequent call. This feature of closure can be used at multiple place where ever the user requires a way to
  • simulate the access to its private properties, or
  • to modify a function on-the-fly where it acts slightly differently for resp Objects, like passing a threshold as the constructor argument which will be different for different objects. 
  • or may be something like $('id').bind where $('id') acts as a jQuery constructor with the html element as the private property of the Object which can always be accessed and "manipulated" by jQuery.
We come across Closures all the times, e.g. all the JavaScript libraries like jQuery, Angular, Underscore etc use Closures as their basic framework of implementation.
Its a great concept, one of JavaScript's very advanced feature, and something every JavaScript programmer should be well versed with. For further details on this interesting concept do visit the following links

Lets move on to Inheritance

Okay so we do not have Extends, Implements, Inherits etc in JavaScript, and we use Prototype instead, lets see how exactly it is used, through a very simple a basic example of Inheritance in JavaScript So as you can see that the we used the prototype magic to simulate Inheritance in JavaScript. Lets just try to understand in detail the logic here.
We have already thrown some light on prototype already in some previous sections, but there are some more light on it. A prototype can be edit in the following ways
  1. By adding more properties to all the existing objects of a type - In this case all the old and new objects will have the newly added properties, as we implemented in first example in the above code example
  2. By adding more properties to an object's prototype - Here all the subsequent instances(and not the previous ones) will have all the new properties, as we implemented in the second example
Hopefully this small post has made it a little easier to understand how and why JavaScript behaves differently than any conventional programming languages when it comes to certain concepts.

Happy Coding,
Sandeep

Comments

Popular posts from this blog

Multi Tenancy with Codeigniter

In this post I will show you how I converted my normal Codeigniter application into a multi-tenant system.(first step to a SaaS implementation) Note - This implementation is a separate DB multi-tenancy implementation. Lets say we have an up and running CI application name ci_app , with the directory structure like this ./application ./application/config ./application/...so many other important directories ./asset ./asset/js ./asset/images ./asset/css ./system ./index.php which is accessed through browser like http://localhost/ci_app So to implement the multi-tenant arch we are most concerned about the following files, and we will be editing them ./index.php ./application/config/config.php ./application/config/database.php And also we need to create a few new ones Create a tenant folder in your www root directory, lets say tenant_1 Cut the ./index.php from ci_app and paste it in tenant_1 directory  Create a blank file config.php in tenant_1 directory Crea

Profiling and checking PHP error_reporting in a Codeigniter App, without editing the config!!

Hi all, You must have definitely used the Profiling in Codeigniter and error_reporting many a times in Development and Testing environment, but I am sure you must have missed it on a real Production environment. As there are scenarios, where you want to quickly debug the Production application and find out what PHP errors is the application throwing, check the page profile, that too without putting the time and effort in replicating the whole production environment on your local machine, or perhaps a testing server. This small piece of code(we could perhaps call it a hack), which I have used in almost all of my CI applications, will make your life very easy, without losing anything on the security of the system. Following points, essentially sum up what exactly it does - Check for the dev(or root or admin, whichever name you use for the su access), if it is logged in, as we don't want others to see all the Profile data and other errors. Check for a specific query str

How I solved design problems by using various design patterns in my Laravel Project

Hey guys, Lately I have been working on a Virtual marketplace application using Laravel and PostgreSQL. So, when I was asked to build this huge application, the biggest challenge I faced was the design. Having a fair bit of prior experience in Laravel and upon following the current community trend, I decided to go with Laravel. And I hoped and expected that this, somewhat opinionated framework, would take care of my design to a large extent. When I actually started designing it, I realized that for a small/medium application Laravel already has things in place, you, as a developer just need to follow the guidelines set in place by the framework and use the features its providing out-of-box. However, for a larger application, with lot of interdependent modules and complex business flows, you need to make your own design decisions as well along with the existing features. This gave me an opportunity to take a look into the various existing design patterns to solve my design probl