Monday, 2 October 2017

The HTML Attributes Never Change!



First things first! What is an HTML attribute?
The html attributes provide additional information about or to the element. For instance value is an attribute below:

<input id="inpt" type="text" value="Roy"/>

Of-course id and type are attributes too, but lets stick to value for the sake of this post.

Without beating the bushes now, lets get to the point!

"An html attribute may or may not have a corresponding DOM property. Similarly the DOM properties may or may not have the corresponding html attribute". For example, the html attribute "value" has a corresponding DOM property "value".

The key point is that attribute values do not change but their corresponding DOM properties do. Consider the following input element:


The attribute "value" is initialized with the value "Roy". Now let's assume that the user changes the value of the input by typing something. Let's observe the values of the attribute and the DOM property.

As can be seen in the grab above, the user changes the value of the input field, the attribute has however not changed and still contains the old value, "Roy", whereas the DOM property is updated to new value "Amjad".

Can you name an attribute, that does not have a corresponding DOM property and vice versa?

Saturday, 23 September 2017

Calling The Super Function In JavaScript



With prototypal inheritance in JavaScript how would you call the super version of a function. Consider Dept that inherits from College as below:


Now you wanted to call displayName() on oDept and you could do that as below:


All of this is simple and cool, but what if you wanted to call the displayName() of College as well from the displayName() in Dept? Something as below:


Notice line-27 where there is an attempt to call the super (College) version of the displayName(). This is however a futile exercise here, as the super is undefined and not recognized. We need to find a way to accomplish this though. Take a look at the solution below:


The trick lies in line-35. Notice that we store the reference to the prototype of Dept in the property uber. You may want to call it super or anything else. Finally it allows us to call the super version of displayName at line number 27.

None of this was possible if we didn't ensure that we had line-34 in place though. Read here if you are wondering why!


Saturday, 16 September 2017

Why is typeof NaN a number?


It's NaN (not a number), but it's typeof is "number". No, really!
Try this:

var iamNaN = 100 * "xyz";

Here, iamNaN becomes NaN for obvious reasons. You cannot expect 100* "xyz" to yield a valid number and so iamNaN gets the value NaN.

However, what's interesting is, typeof iamNaN returns "number". The question is, if iamNaN is NaN (not a number) then how on earth can its data type be a number?

typeof iamNaN; // gives "number"
isNaN(iamNaN); // gives true

Also, why is typeof a string not "number"? After all, a string is also a NaN.

var whyNotMe = "hello";
isNaN(whyNotMe); // gives true

typeof whyNotMe; // yields "string"

iamNaN contains a value that is not a number, and so does whyNotMe. Then why is typeof iamNaN a "number" and not that of whyNotMe?

The ECMAScript standard states that Numbers should be IEEE-754 floating point data. This includes Infinity, -Infinity, and also NaN.

You will find a few more similar arguments floating on the web which tell you why typeof NaN is a "number". This blog however, has a very simple logic to justify the typeof iamNaN to be a "number" and not that of whyNotMe.

Consider this:

What would you call an engineer A, who successfully passes his final exams? A passed engineer or may be just an engineer. Now, what you would you call an engineer B, who just failed his exams? Probably a failed engineer, or may be just an engineer. So, both A and B are engineers, and it just happens that A is a passed engineer and B is a failed engineer. iamNaN (not a number) is like B here. It's a failed number. Just as the typeof B is an engineer (even if failed), the type of iamNaN is a number (even if failed)

In contrast a medical student who passes or fails his exams can never be called a failed engineer. This is exactly why typeof whyNotMe (a string) can never be a "number".

You should now be able to digest the fact that typeof NaN is indeed  a "number"!

isNaN(true) // yields false
Can you guess why?

Friday, 25 August 2017

Why You Must Reset The Constructor!


In my last write up, we realized the beauty of the constructor property of an object. We discussed how easy the said property made it for us to create an object of the same type without having direct access to the function that creates the objects.

So, where does the constructor property come from anyway!

When you access oStudent.constructor, you get the access to the constructor function of oStudent. However, oStudent does not contain the constructor property. Take a look at the snapshot below:



As can be seen in the watch snapshot above, the object oStudent does not contain any property in the name of constructor. So where does it get this property from? Recall my post on prototypes, and you will realize that the property comes from the prototype of its constructor function. Assume that the constructor function of oStudent is Student, and so lets watch prototype of Student below:


Voila! there it is. The property constructor comes from the prototype of the constructor function (Student) that created our object oStudent. Now, we know where the constructor property comes from, when you do oStudent.constructor.

So, what does this have to do with constructor resetting?

Again if you go back to my discussion on prototypes, you will know that you could augment (add) properties to the prototype of a function. You could add any number of properties. However, at times you may also want to replace the prototype itself, with your own object. In that case, you will have replaced the default prototype of the function with your own function, as below:


The trouble with doing this is, you lose the constructor property that the default prototype had. See what our new prototype contains vs what the original prototype contained:


On the left we see that the original prototype contains the constrictor property, but on the right the new prototype that we set does not have it. So therefore any new objects created from the function Student will not get the constructor property. So you will not be able to make use of the constructor property of the object if you wanted to.

How do I ensure the constructor property is not lost?

When you replace the default prototype with your own object, make sure that your new prototype keeps the constructor property. Below is how you would do it:


Simple, right! but extremely useful. Look below, how our new prototype looks now:


There you go! Our prototype now has the necessary property 'constructor'. Now, all new instances of the function Student will have access to it.

Can you now guess the output of lines 16 and 25 below?


Give it a shot and find out!


Friday, 18 August 2017

An Object Just Like You, But Not You!




If you have read my last blog on prototypes, you will know that you could use functions as a machine to create objects. Such functions that create objects are called constructor functions. Now let's say you have an object 'objJustLikeYou', and you want one more (or may be few more) object(s) like 'objJustLikeYou'. You do not want to clone it as that will simply give you a copy of the object as it exists in the current state. You do not want that but an object like objJustLikeYou in the original state. A copy will give you objJustLikeYou with properties that may be in a different state (current state of objJustLikeYou) than the original state when objJustLikeYou was freshly created.

In other words, when objJustLikeYou was created, it had the property say 'x' in a sate x=0, but now the state is x=100. So, if you opt to make a copy of objJustLikeYou, your new object objJustLikeYou2 will also have the state x=100 which is not your objective. Your objective is to get an object like objJustLikeYou but in the original state irrespective of what state the objJustLikeYou is in.

In summary, you want to get hold of the constructor function that created objJustLikeYou and get it to make one or more fresh objects for you. The trouble is you have no access to its constructor function, or do you!

This is where you could use the constructor property of your object objJustLikeYou. See the code below:


Now that you have the constructor function, you could have all the fun you want with it. Let's create an object out of it now.


You could create n number of such objects from the constructor function.

A very important point to note here is that the property "constructor" comes from the prototype of the constructor function of objJustLikeYou. So, when you say objJustLikeYou.constructor, it doesn't come from objJustLikeYou but from the prototype of its constructor.

objJustLikeYou (no constructor property) -- Constructor Function -- Prototype (has constructor property)

Wonder what will be the constructor function of the object below?


Give it a shot and find out!

Sunday, 13 August 2017

The JavaScript Prototypes!


Functions are first class objects in JavaScript. If we are to believe that functions are objects, then they will have some properties. A very useful property of a function is "prototype". So if you had a function myFn, it will have a property in the name of prototype!
Every JavaScript function has this property (prototype), however this property is useful when you use the JavaScript function as a constructor function and not like a normal function. In other words, you can also use JavaScript functions as constructor functions, i.e. create objects out of them. Take a look at the cod below that uses the function Student as a constructor function:
At line-12, we create an object using Student as a constructor function. We could create hundreds of objects out of Student. Now, recall our previous point about functions having the property prototype. It implies that Student must have this property as well, and you bet it does! So, you could access Student.prototype.
A property alright, but what is a prototype anyway? An object! "Yes, the prototype property simply points to an object". There's more, so keep reading... :)
Just as with any object, you could augment (add) properties to the prototype object too. As can be seen in the lines 14 and 15 above, we use the prototype property of the function Student to store a couple of properties in it. Please note that prototype is a property of Student and not of oStudent. In other words, its a property of the constructor function and not the objects created out of the constructor function. A lot of people erroneously try oStudent.prototype and that's wrong!
"An extremely important point to note here is that all the objects created out of Student will have access to the prototype property of Student". Which means, oStudent.university will give you "University Of Pune", although oStudent itself does not contain the property university.
Line numbers, 24, 25 and 26 above have objects accessing university and they will get the values! This is because, "all objects of the constructor function will have access to the prototype of their constructor function".
So how does it work? When you access oStudent.university, the JavaScript engine looks to see if the object oStudent contains the property university, which it doesn't in this case. The next thing the engine does is, it looks to see if the constructor of this object has a prototype and if that contains it. In this case the property is found in the prototype and fetched. On the contrary, if you had accessed oStudent.name, the JavaScript engine would once again first look up into the object oStudent and look for the property name, which it would find in this case and that would end the lookup process.
Based on our discussion, what would the following code (line-14) output to?
That's right! the out put will be Tom. The JavaScript engine will find the property name in the object oStudent and never bother to look any further!
Remember, any and every object of Student will only have access to the prototype, and not own the properties of the prototype. So, if Student.prototype.unveristy changes, it changes for all objects. The prototype properties are therefore shared commonly among all the objects. Objects simply have access to prototype, they don't get their own copies of what prototype contains!
There's more about prototypes! Did you know, prototypes are the JavaScript's answer to inheritance - the "prototypal inheritance". I may just write an article about that some day :)

Understanding The JavaScript Closures!

If you have read my article on Variable Hoisting In JavaScript! then you know that there is only function scope in JavaScript and no block scope. We take this understanding a step further and explore closures now!
To understand closures, let us first understand what inner functions are. Take a look at the function innerFn below:
Functions are data in JavaScript and a function could contain data and hence another function too. In this case, outerFn contains innerFn and the innerFn becomes our inner function as it is scoped within outer function outerFn. Because there is function scope in JavaScript, the following points apply:
  1. The variable x is declared in the global space (window) and therefore is accessible everywhere.
  2. The variable y is declared inside outer function (outerFn) and hence is accessible everywhere inside the outer function (outerFn). This implies it is accessible inside the inner function (innerFn) too.
  3. The variable z is declared inside the inner function (innerFn) and hence is accessible inside the inner function and not outside of it.
  4. The inner function (innerFn) will always have access to the outside world as it is global to it. For example, it will have access to the content of outer function and global space. If inner function contains another function, say innerFn2 then the innerFn would not have any access to the content of innerFn2 but innerFn2 would have access to the content of innerFn, outerFn and the global space.
Inner functions are the private functions:
You can access outerFn from global space because it is declared in the global space. You can however not access innerFn from the global space, simply because innerFn is scoped within outerFn (remember function scope). Creating inner functions is therefore the JavaScript way of creating private functions. In this case, innerFn is a private function to outerFn and it cannot be accessed outside outerFn.
Difference between inner functions and closures:
So, what are closures then? Are they simply the inner functions? The answer is both yes and no! It should be noted that all closures are inner functions but all inner functions are not closures!
What makes an inner function a closure?
Take a look at the code snippet below:
With the above example, we have just broken the encapsulation. We accessed the innerFn from global space although innerFn was scoped to outerFn and not accessible outside. We did it by simply returning the reference of the function.
There is another way to break this encapsulation. Below is how you can do it as well:
This time we did it using a global variable. The global variable can be accessed anywhere and we used it to our advantage by storing the reference of innerFn inside it and then accessing the function outside. And yes, we again broke the so called encapsulation.
How does this breaking of encapsulation compliment our discussion on closures? When you break this encapsulation and call an inner function from outside its enclosing function, the inner function becomes a closure!
Most important characteristic of closures:
In the above example when you call outerFn() and outerFn finishes its execuation, the variables inside the function are destroyed soon after. This implies that the variable y which is scoped within outerFn will be destroyed soon after it goes out of scope i.e. the outerFn has completed its execution.
What happens when you call the myInnerFn() soon after(line-26)? Note that inside innerFn, we access the variable y (line-18). Do we get the reference of y, as it is supposed to have been destroyed already after outerFn completed its execution? The answer is yes! The innerFn will have the reference of y although the variable is supposed to be already out of scope by now. The reason is that closures maintain the references of the variables of their enclosing function (outerFn) even though the enclosing function has already completed execution and the variables are supposed to be gone! This is the beauty of closures.
Closures therefore are the inner functions that are accessed outside their enclosing functions and retain the references of variables in their enclosing function, even though the enclosing function has completed its execution and the variables are scoped out.
If you think closely, the outerFn, which is declared in the global space is also an inner function. Do you agree?

Variable Hoisting In JavaScript!

Guess the output of the code snippet below, and that shall set the context of our discussion:




Line-10 outputs to undefined, and line number-14 to 200. If you had guessed the same output then you probably understand variable hoisting in JavaScript but you had expected line-10 to output 100 and line-14 to output 200, you must read on!
Unlike many other languages, there is only function scope in JavaScript and not block scope (ES6 allows block scope with let though). This implies that a variable is accessible everywhere in a function irrespective of where the variable is declared within the function like below:
In the above example, the variable x gets declared inside a block (for loop block) but this doesn't limit the scope of x to the block but everywhere in the function fn. There is absolutely no block scope in JavaScript irrespective of the type of block. JavaScript only has function scopes.
So, how does this compliment our discussion of variable hoisting? Because there is function scope in JavaScript, "JavaScript hoists or elevates all variable declarations that it finds in the function to the top of the function. Please note, only the declaration part is hoisted or elevated and not the definition part (value assignment)". This means, the code snippet below on the left is converted into the code snippet below on the right, by JavaScript.
As you can see in the code snippet on the right above, JavaScript has hoisted the declaration part from line-12 in the left image to the line 10 on the right image, but hasn't hoisted the value assignment. So, now if you had to guess the output of code on the right, you would correctly guess it to be undefined for line-10 and 200 for line-14.
So, in summary it should be remembered that variable declarations get hoisted in the functions called the variable hoisting.
Wonder what happens to any functions declared in the function? Do they get hoisted too?

Simplifying The Difference Between undefined and null

Most of us find it confusing to differentiate between undefined and null variables in the JavaScript world. Here is my attempt to simplify it.
If a variable is undefined implies that it has not been defined. This essentially means that the variable has not been given a value. For such variables that have been declared and not defined (not given a value), JavaScript assigns it a special value 'undefined'. Therefore the data type of such a variable is undefined in this case. By the way this also implies that undefined is a data type in JavaScript and belongs to the pedigree of primitive (simple) data types. Let me summarize the undefined variables by saying that 'these are the variables that are declared but not defined/initialized'.
Now then about the other guy, the null variable! Unlike in the above case, the null variable has a value, the null value. The variable was initialized and given a null value. The null value belongs to the pedigree of objects.
From the above discussion, a simple difference between undefined and null could be put up by saying "undefined variables are the declared variables that never got initialized whereas the null variables have been initialized and have the null value".
However, the similarity between the two is that they are both falsy values! Having said that undefined === null is not true! Did you know why?

The HTML Attributes Never Change!

First things first! What is an HTML attribute? The html attributes provide additional information about or to the element . For instan...