One of the secrets to being a super effective developer in any language is to truly understand the semantics of the language. In this post we will cover basic parts of Javascript semantics.
Variables are References
Variable in JavaScript is simply a label that references a value in memory in heap. These values can be primitives like strings, numbers, and boolean. They can also be objects or functions.
Local Variables
In the example below, we will create four local variables in the top-level scope and point them to some primitive values:
var name = "Pankaj";
var age = 28;
var isProgrammer = true;
var likesJavaScript = true;
We can now test isProgrammer
to likesJavaScript
by strict equality comparison. They both refer to same value of true in heap
isProgrammer === likesJavaScript;
Notice that the two boolean variables point to the same value in memory. This is because primitives are immutable and so the VM can optimise and share a single instance for all references to that particular value enhancing performance.
In the code snippet we checked to see if the two references pointed to the same value using ===
and the result was true
.
The outer box represents the outermost closure scope. These variables are top-level local variables, not to be confused with properties of the global/window object.
Objects and Prototypes
Objects are just collections of more references to objects and prototypes. Only special thing is that prototype chain is added when we try to access a property that does not exist in local object; but in parent object
// Create a parent object
var raam = {
name: "RAAM",
age: 28,
isProgrammer: true,
likesJavaScript: true
}
var pankaj = Object.create(raam);
// Override some properties locally
pankaj.name = "Pankaj";
pankaj.age = 4;
// Look up stuff through the prototype chain
pankaj.likesJavaScript;
In example above; we have four properties referenced by raam
variable. Then we created a new object pankaj
from the first object raam
. Now pankaj
object references raam
object. Then we overridden some properties in pankaj
object
Now when we access pankaj.likesJavaScript
, it first looks into, pankaj
object; since it does not find it there, it traverses to parent object raam
and finds it there. One can think of this as layering one object over other.
Global Object/Variable
In JavaScript, global variables/object available to entire scope and lifecycle of underlying JS engine. That’s why it is not garbage collected even when not in use; thus use of global variable/object are discouraged.
Declaring a variable of object without var
is considered a global variable/object. So always remember to use var
while declaring variable/object. Consider following example
var name = "Pankaj";
var age = 28;
var isProgrammer = true;
// Oops we forgot a var
likesJavaScript = true;
Notice that likesJavaScript
is now a property of the global object instead of a variable scoped in the outer closure.
When we are writing a script that is going to be mixed or used with other scripts; this can interfere with there working given there is conflict in variable/object names used
Always remember to put those var
statements in there to keep your variable’s scope to the current closure and its children. You’ll be much happier by following this simple rule and would avoid namespace conflicts.
If you must put something on the global object, do it explicitly in window
object in browser.
In Node.JS; one can attach global variables to
globals
object
Functions and Closures
JavaScript isn’t just a series of chained data structures. It contains executable, callable code known as functions. These functions create chained scopes and closures.
Visualizing Closures
Functions can be drawn as special objects that contain executable code as well as properties. Every function has a special [scope]
property that represents the environment it was in when it was defined. If a function is returned from another function then this reference to the old environment is closed over by the new function in a “closure”.
In example below; we will create a simple factory method that generates a closure and returns a function.
function buildClosure(name) {
return function () {
return name;
};
}
var closure1 = buildClosure("RAAM");
var closure2 = buildClosure("Pankaj");
console.log(closure1());
console.log(closure2());
When we call closure1()
, the VM looks up the function that it references and executes it. Since that function looks for a local variable named name
, it finds it in the closure scope. This factory method is nice since each generated function has its own space for local variables.
Shared Functions and this
Sometimes for performance reasons, or because you just plain prefer the style, JavaScript provides a this
keyword that allows you to reuse a function object in different scopes depending on how it was called.
Here we’ll create a few objects that all share a common function. This function will reference this
internally to show how it changes from call to call.
var raghu = {
name: "Raghu",
description: function () {
return this.name;
}
};
var description = raghu.description;
var shyam = {
description: raghu.description,
name: "Shyam"
};
console.log(raghu.description());
console.log(shyam.description());
console.log(description());
console.log(description.call({
name: "Raam"
}));
In the diagram, we see that even though shyam.description
was set to raghu.description
, it’s really only referencing the function. Thus all three references have equal ownership of the anonymous function. This is why I try to not call functions on constructor prototypes “methods”, because that implies some sort of binding of the function to the constructor and its “class”.
Stay Tuned for next part <3
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM