Internals of Variables in Javascript

Javascript being the subset of Java (with almost no similarity), at least some people think when Netscape announced it way back, is widely getting popular nowadays (outside web world) because of its flexibility on defining objects and its prototypes. Javascript is truly flexible language and has been great when dealing with Web architecture, where things are totally flexible too with HTML or XML. It follows no standards, no rules, and even no object oriented technologies.

Everything in Javascript is an object or an Array. For instance, Object prototype adds some functions to every objects in javascript like toString(), toSource, valueOf etc. These properties exists in every single objects inside javascript.

Javascript stores everything in Arrays. For instance, when you declare a variable in global scope, it will actually add the variable to the array present in Window object. You wont feel it, but internally it does like that.
Similarly, when you define a variable, the javascript engine internally adds the variables to an array declared in the scope chain. Even though you cannot access the private variables declared in the scope chain using a loop, but you can use loop to get the variables declared in public scope.

For instance,

function printFunc(){
var name;
for (name in this) {
alert("this[" + name + "]=" + this[name]);
}

Now if you call the printFunc, it will enumerate all the properties associated in the array using this[name] and get you values of all the variables. It is worth noting, this[“printFunc”] will hold the body of your Function as well. 🙂

Yes, I am telling you, everything in Javascript is an array. Lets say I call my printFunc with some arguments,

function printFunc(x, y, z){
for (n = 0; n < arguments.length; ++n) {
arg = arguments[n];
alert("typeof arguments[" + n + "] = " + typeof arg);
for (name in arg) {
alert("arguments[" + n + "][" + name + "]=" + arg[name]);
}
}
}

In the above code, the printFunc will print all the arguments passed to the function. The Function automatically defines an array arguments and pushes all the arguments there.

Is it all about Prototypes ? 

Well, yes, perhaps. Everything in javascript follows one single standard, that is prototype. For instance, Object.prototype defines few methods like toString(), toSource() etc. Each variable in javascript automatically gets access to them even if they are of primitive types.

var x = 10;
alert(x.toString()); //typeof(x) == "number", a premitive type, yet it can access toString()

What about Functions ? 

As I told you, Javascript follows no rules. Functions are some lines of code that executes when called. Functions are called either using apply or call (both these methods are defined within the Function prototype). When a function is called using

func();
func.apply(null);
func.call(null);

All of them are same thing. The javascript actually uses apply / call native methods added to the Function prototypes to call a method.  As I told you, every object also inherits properties from Object prototypes, you can get the whole body of the func by calling :

alert(func.toString());

Differences between Arrays and Json ?

Both are actually object representation of Collections in Javascript. Arrays follows the simplest object store, where the key is an integer. There is also a type defined for Array using Array.prototype. The Array can be declared in shortcut like : [] in javascript.

Similarly, JSON even though representing a serialization of object, it is also a representation of collection in javascript where the key is a string rather than an integer (in contrast to Arrays). JSON can be represented as {} in javascript.

var arr = [];
arr[0] = "Abhishek";
alert(arr[0]);

var json = {};
json["name"] = "Abhishek";
alert(json.name);

Array is taken as a primitive type in Javascript and its prototype natively adds some functions like length, push, pop etc.

Some info about Scopes :

Well, scoping a variable also follows few strange rules. A variable has a scope associated. A variable declared within a scope adds to its scope chain only, and can only have access to the scope where it is declared or any scope created from there.

One of my friend asked me the differences between
var x = 10;
and
x = 10;

Well, initially I thought the browser will throw an exception when it does not find the variable declared, but it does the other way. With option strict turned off, the browser will try to find the variable x in its scope and all the way to its parent scopes until it gets to the Window object. Lets frame this in other words :

var x = 10;
//means x will be local to the scope it is declared to.

//On the other hand,
x = 10;
//will mean it will try to find parent scope one after another to reach window.

So if nowhere x is declared, it will be

alert(window.x);
alert(window[x]); //same thing

The object x will be added to the local window object.

Another fact is, Irrespective of where it is declared with or without, the browser engine is well capable of checking the prototypes properly. So for instance, alert(typeof(x)) will say it as “number”.

There is another diff as well, if x goes to the global scope, it automatically secures it using properties. According to ECMA standards, each property prototype has ReadOnly, DontEnum and DontDelete flags, in case of declaring without var, you will see the DontDelete flag is set to false while with var it is true.

ReadOnly = false
DontEnum = false
DontDelete = false

Yes I am telling you the truth, you cannot get the flavor of this because they are declared natively. Although you can try to get the value of DontEnum flag using propertyIsEnumerable function declared in Object prototype. Just calling,

window.x.propertyIsEnumerable()

The value will be returned as false.
I told you the DontDelete flag is set to false when the object is pushed to Window. Lets try to prove my statement.
To see the actual effect, you can try deleting a local variable :

var x = 10;
y = 10;

assuming y doesn’t exists in anywhere, if you do

delete x;
// false (which suggests DontDelete is set to true.)

delete y;
//true (which suggests DontDelete is set to false, and object actually gets deleted.)

Hence you can say, global variables can be deleted while locals cannot.

Conclusion

Javascript is a funny language. It is not strict to its type, or even not strict to its flexibility. It is very slow, and almost unusable in professional applications that needs throughput. But,  It is one of the most flexible languages ever built, interpreted and hence much more suitable for browsers where client executes a small amount of code using CPU slices.  There are a lot of hidden secrets I can talk about Javascript which might take a long time. I will try to add more to the Javascript internals when I get more time.

I hope you like this post.

Best regards.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

2 Comments to “Internals of Variables in Javascript”

  1. Cristi Paraschiv

    “Javascript being the subset of Java” – since when? Please read a little about Javascript’s history before stating that.

    That statement made me skip the entire article, you haven’t properly done your research.

  2. Abhishek Sur Author

    Its debatable yes.. because you will see there is no similarities between java and javascript. I like Java as a language, being its type safe and compiled, but for browsers javascript is the only language you can deal with.

    From Wikipedia :
    “Battling with Microsoft over the Internet, Netscape considered their client-server offering a distributed OS, running a portable version of Sun Microsystems’ Java. Because Java was a competitor of C++ and aimed at professional programmers, Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft’s Visual Basic”

    If you check the history, Javascript is initially taken from Java, but ECMA people found java to be not suitable enough to run with HTML and they changed it to Javascript.

    I hope this would clear your understanding. Read the article, I hope you will like it.

Comments are closed.