Understanding JS: Prototypes

January 29, 2010
vitruvian octo

Obligatory 'art'. Vaguely on topic perhaps?

To employ laziness.

In JS any object can have a special link to another such that if JS cannot find a key-value pair in the former, it also looks in the latter before failing.

Looking up a hierarchy is the essence of inheritance and the special link that forms the hierarchy between two standard objects is the defining feature of prototypical inheritance. JS, as is now obvious espouses prototypical inheritance.

In prototypical inheritance, the object that carries the special link is called the instance and the object to which it links to is called its prototype.

Note: As this topic is one of the rat’s nest that JS is notorious for and also a very puzzling juncture where most beginners go home, I’m going to go ahead and do something drastic to alleviate some of the pain usually encountered while tackling this topic. Sure there’s no gain without pain but trust me, there are worthier causes. With that, I’m going to pretend that the ECMA standard, IE and Opera doesn’t exist! We sure will bring them back into the fold. But that’s only much later. But to make painless progress in this front, ignore them. For now.

So by now you should be running interpreters provided by the house of Mozilla and the family of KHTML (Chromium, Webkit, et al).

Let’s consider that for our program, we have lots of objects similar to these two.

var flub = {
    color : "green",
    size : 20,
    speed : 40,
    weapon : {name : 'slime', ammo : 100}
},  blob = {
    color : "red",
    size : 20,
    speed : 30,
    weapon : {name : 'slime', ammo : 100}
};

We immediately see that these objects have common key-value pairs (properties). So to save us some typing (more than anything else), we make an object having the common properties and set it as the prototype of all the objects that needs these properties.

As a consequence, we get for free the ability to centrally tweak the common properties of all the instances of that prototype, also, in the process of naming the prototype object, we may attain a deeper insight into our program. After all, prototypes (as defined by the dictionary) are a convenient forgetfulness (abstraction) that represents similar objects.

So here’s how we go about doing that.

Create the object that will act as the prototype.

var thingy = {
    size : 20,
    weapon : {name : 'slime', ammo : 100}
}

Create the objects that will act as the instances.

var flub = {
    color : "green",
    speed : 40
},  blob = {
    color : "red",
    speed : 30
};

This doesn’t look like much of a saving. But you’re only saying that because we’re only dealing with a few objects. You’ll quickly change your opinion (as I’m sure you will) when dealing with hundreds of similar objects in real programs.

Okay, you say. We have some objects.. now what?

Enter __proto__ the non-standard unreliable hero.

See,__proto__ is a modifiable key that objects created by the implementations mentioned previously provide. Assigning to the __proto__ property of an object causes it to inherit (be the instance of) the assigned object (prototype). Thus.

flub.__proto__ = blob.__proto__ = thingy;

You should from the previous post know that = operator is right associative and that its value is the assigned object leading to a cascade that sets both flub.__proto__ and blob.__proto__ to refer to thingy.

Accessing a non-existent value from an instance will cause JS to follow the hidden link (__proto__) up the hierarchy looking for what we asked it to find.

So… You may visualize what we did as follows.

prototypes

Squint really hard. There you go!

Looks pretty complicated but that’s only because we’re looking at the all at once exploded view. Imagine the exploded view of your mobile phone (using which is of-course second nature) for contrast.

When actually using objects, we should be at ease as using a mobile phone. Because with practice and with programs having numerous objects, we won’t be thinking about it all at once. We’d be employing the hierarchical nature of our thought process to forget most of the detail. A session on the REPL should help cement some of these ideas.

Refer the diagram above, and trace JS’s activity through it.

>> flub.color //As expected. 
>green
>> blob.color //Same
>red
>> flub.size //JS looks up the prototype chain to thingy and gets size from thingy.
>20
>> flub.weapon.name //We can keep qualifying as needed and JS follows along.
>slime
>> blob.weapon.name //Same as above. But from a different object.
>slime
>> blob.weapon = {name: 'laser', ammo: 40}; //Mew weapon object assigned to blob
>[object Object]
>> thingy.weapon.name //But not to the prototype (thingy)
>slime
>> blob.weapon.name //Blob has its own weapon.
>laser
>> blob.__proto__.weapon.name //Explicitly asking JS to follow __proto__.
>slime
>> flub.weapon.name //Flub has no weapon. JS follows the proto chain.
>slime
>> thingy.size = 100; //Assigning to the prototype object directly.
>100
>> flub.size //Leads to dynamic changes in its instances.
>100
>> blob.size //Same as above.
>100
>> flub.__proto__.size = 40; //Assigning to prototype via the __proto__ reference.
>40
>> blob.size //As expected.
>40

At its core, this is all there is to JS’s flavor of prototypal inheritance. The rest is all JS’s self important posturing. The ECMA standard hides the special link (__proto__) and goes on in a round about way how to achieve more or less the same thing.

But we cannot wrangle JS like this in polite company and we sure should learn to be diplomatic and standard compliant with JS. But that’s for later. For now, we can rest assured at having the upper hand.

Activities.

  • More REPLing.
  • Try chaining objects using __proto__.

Understanding JS: Objects

January 25, 2010
Object

When wrappings is the gift.

The unit of JS thought.

The term “object” is used very loosely in JS. Let’s just consider the typical and most common meaning.

Like the other values we’ve seen so far (strings and numbers) objects too are values. Consequently, they can be assigned to and be referred by variables.

Without further ado, let’s just create one.

var flub = {};

That’s it. Creating an object is as simple as that.

This is flub.

Visualize the curly braces as this. If you must!

This one is empty, thus of not much use. The real purpose of an object is as a: collection of key – value pairs . A key value pair is a name (key) and the value (any JS value) that the key refers to. Thus it is very much like a variable and the value it refers to. So a collection of those is quite like a collection of variables.

Why do we need collections? For almost all the same reasons we need collections in real life. Primarily to fit stuff into our head and forget details.

A computer is a collection of parts and functions. So is a car. Do we need to know all the complicated details of their implementation to use these objects? Surely, nobody likes to manipulate and think about the myriad constituents of such complicated machines to use them and get something done.

Collections appear to be a feature of our brain. We certainly do extend that to the physical world. We combine and group things in the physical world and we let the world worry about the storage, maintenance and mirroring our ideas. We go on in our daily lives, operating on top of layers upon layers of such convenient forgetfulness (abstractions) and don’t give much thought to it.

JS allows us to transplant those skills into the digital realm and objects play the central role in allowing us to do so. After all, everything IRL is an object with a name.. right?

Two forms to manipulate objects.

Lets visualize these two ““, “” to be JS values (remember values could be any of string, number, object etc)

Then this var blob = , spike = ; will give us

blob and spike

As you probably know.

To add a key-value pair to flub, we could use either of the following syntax.

flub["friend"] = blob;
flub.enemy = blob;

Giving us.

flub's relation

flub looks confused.

Don’t worry we can fix that. To fix flub, we need to update one of its keys. We could do that either..

  • flub["enemy"] = spike; this way.
  • flub.enemy = spike; or this way.
flub hates spike

flub hates spike. flub isn't confused anymore.

Accessing values of members is also quite intuitive. You do either

  • var flubsEnemy = flub["enemy"]; this.
  • var flubsEnemy = flub.enemy; or this,
flubsenemy

We can keep tabs on who's who.

The form of these manipulations with the dot separating the object name and the key is called the surprise surprise dot notation. The other with the square brackets flanking the expression that stands for the key is called the subscript notation (also known as the bracket notation).

Hmm… “the expression that stands for the key”..

Here, take a look at this.

dot notation

flub and enemy are names as is.

subscript notation

flub is a name as above. The area in red flanked by the square brackets can contain JS expressions. JS converts the value of the expression to its text representation before doing the rest of its job.

Conveniences all around.

To quickly create and populate an object, JS gives us a colon separated notation for key-value pairs which you can delimit by commas and flank by a pair of matched curly braces.

var score = {
    player : “you”,
    points : 1,
    avatar : blob,
    inventory : {} //object inside another object.
};

scores

Yes! We keep scores.

The curly braces syntax including the empty one that initially created flub is called the object literal syntax. Why literal? Because it stands for what it is.. no funky manipulation here.

Summary.

  • Collect stuff together and give it a name.
  • Simplify problems by breaking it up.

Understanding JS: More about Variables.

January 22, 2010
Like tags.

Sort of like tags.

A value named blob.

Say we have a JavaScript value “blob“.

Then if we could do something like var blob = blob ; what would be the meaning (semantics) of what we just asked JS to do?

  1. We know from our previous discussion that the var keyword in conjunction with a name is used to create something called a variable.
  2. And that when we assign a value using the = operator, JS somehow put the value in the variable.

#2 is rather simplistic and indeed misleading. The meaning of “assignment” with respect to JS is more subtler than that.

What var blob = blob ; really means is as follows.

  1. Create a reference (think a link) to blob which exists in memory.
  2. Create a variable named blob and update it with a reference to blob

Key idea: Assignment (=) creates references. Variables contain references.

We shall see the consequences of that in further detail.

Let’s consider the meaning of var thingy = blob; Note that we are still continuing the session from above and thus blob still refers to blob

  1. Create a variable named thingy.
  2. Refer thingy to what ever blob is referring to. (In this case blob).

Gratuitous Graphic:

blob-thingy

Thingy and blob refers to the same thing.

no-thingy-blob

WRONGO! Okay?

Another example and more gratuitous graphics.

Consider “” and “” to be JS values.

With that, let consider the meaning of the following.

var ball, sphere;

ball-sphere

vars ball and sphere defined.

ball = ; Note, we’re not using the var anymore as ball has already been declared..

ball-sphere

ball refers to it's assigned value.

sphere = ;

ball-sphere-referring

ball and sphere are referring to their respective assigned values.

ball = sphere;

ball-sphere-garbage

ball is not referring to it's original value anymore.

As far as we are concerned, the value that ball was originally referring to is lost. We have no way of referring to that anymore. It’s beyond our reach. JS sees this and based on the assumption that we have no use for it anymore, eats it.

Some people call this process “Garbage Collection”. But that sounds a bit haughty don’t you think?

About primitives.

Primitives are assigned and manipulated via variables quite differently from the above. But the rat’s nest complexity of this topic can be simplified by thinking of primitives as immutable (unmodifiable) that are always referred to by the literal notation of these primitives. Ie: There is only one value for each primitive existing in memory. Say the number one or the string (foo) is always referred to by it’s literal syntax. 1 and "foo" respectively. You can also think of them as not being eaten by JS (garbage collected) when no variable is referring to them because of this.

Summary

  • Variables are more like tags than boxes.
  • Variables contain references that point to values.
  • A value can be referred by many variables.

Understanding JS: Conquering by naming.

January 18, 2010
Stuff in boxes.

Stuff goes in boxes, boxes have names.

Naming is half the battle.

What would humanity do without names…? When we think about it, it slaps us across the face. Every word you know is a name. Names upon names augmented by your senses is all you really know. I think names define humanity.

..

Even though programming isn’t as awe inspiring and terrifying as real life, just as in real life, here too we manage complexity by naming things. And in JavaScript, we name values.

Before you commit that to your memory, realize that by values, we don’t only mean the few rigid values we’ve come across so far. Even though JavaScript offers only a fraction of the working space of natural languages, it’s not that dumb. It can also name some soft, pliable and sometimes “live” kind of values (data types) we’ll save for later consumption. To sneak a peek consider that these latter values allow us to group lesser values and operations.

So yes; as in the spirit of how we make sense of and communicate about things IRL, JS allows us to name essential values, groups of stuff, operations and their conjugates allowing us to make sense of and communicate with the person and machine that reads our code.

When we define a name for a value, in JS we refer to this name as a variable.

It’s Play time.

In JS we name values using the var keyword. (A keyword is a name that has a special meaning to JS. Unlike operators, keywords do not manipulate data. They only instruct JS to do something different. Note that you cannot use any of these keywords as names, refer footnote for list of keywords).

Defines a variable named box.

>>var box;
>

Assign the value 10 to box using the = operator. We don’t need to use var keyword again for this name. Also note that when we assign, JS REPL prints the value of the assignment. This suggests that = is an operator and returns the value that it assigns. Thus the value of box = 10 is 10 with the side effect that box now refers to 10.

>>box = 10;
>10

Check if JS remembers our definition.

>>box  //variables evaluate to the values they refer.
>10

All in one definition. Note the absence of a return value. var is not an operator.

>>var tote = 20;
>
>>tote
>20

JS isn’t strict about the type of stuff we put in variables. (JS is loose-typed) Neither is is fussy about us reassigning as and when we please. Remember we assigned 10 to box.

>>box = "you"; //I just put "you" in the box. So now it has a string.
>you

Since its only the value that matters, I can put “you” in a box and a tote simultaneously!

>>tote = box;
>you
>>tote
>you
>>box
>you

I can play wizard and do this.

>>tote = box = "me";
>me
>>tote
>me
>>box
>me

Assignment (=) is right associative. With the assignment operator =, it’s operands hugs to your right. If you wanted to manually group what happened, it’d look like this. (tote = (box = "me")) contrast this with 1 + 2 + "3" from the previous post.

>>var x = y = z = "Some Value.";  //It means just as you would expect. Test it in your REPL.
>

If you want to define and initialize many variables, JS offers a shorter way to do that in one go rather than to use many vars. Only one would do.

>>var a = 1, b, c = "see"; //so on and so forth.
>

CAUTION

If you did not use var before you assigned a variable; JS goes ahead and does it for you in such a way that the variable will sooner or later turn around and bite you in the neck. We’ll see why this is so. But for now, cultivate this habit of always declaring your variables with var.

Keywords and reserved keywords.

You can’t use these as names. Some are meaningful to JS, others are reserved for future use.

abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with

Home work.

  • Play with the REPL.
  • Try to confuse JS into a corner.

Summary.

  • Naming is abstracting. We name to forget details and manage complexity.
  • I don’t know what we’d do without names.
  • Don’t ask JS to implicitly declare variable for you.

Understanding JS: Like building with bricks.

January 16, 2010
Building with bricks.

Like a brick layer.

Like building a house.

Just as a builder isn’t expected to manufacture the materials and tools of his trade, a programmer is only concerned with the analogues of ready-made types of materials (primitive data types), basic tools (operations) and the usage instructions (syntax rules) that the programming language provides.

At the most essential level, operations are done on members of data types. These specific instances of data types are called values. And the syntactic beings that operate on values (do the operation) are called operators.

It about time we played with some values of a few types and some operators that manipulate them.

We need values of different types. The rest should follow.

Numbers: Just what they sound like. But not so average and not so run of the mill (the devil is in the details). But for our immediate purposes, they’re just what they sound like! Numbers are definitely useful. They sure are good looking building blocks.

//This is a comment. Lines that begin with // are ignored by JS.
//Comments are usually meant for humans.
//Things following the '>>' signifies our input.
//Things following '>' signifies JS's output.
//Numbers evaluate to themselves. They stand for themselves.
//JS isn't doing any work to derive its value.
//It's just what it looks like. It's primitive.
>>1
>1
>>420
>420

Strings: Strings are sequence of characters flanked by single quotes or double quotes but with the condition that they must be matched. There are some caveats but we’ll cross such bridges when we reach them. (Yes, lot of bridges to cross). Strings signify text. Text is useful right? You could use them for like what a millions things? Sure. So they are yet another primitive data type.

//Strings too evaluate to themselves.
>>"How's it going?"
>How's it going?
>>'She said; "Not too bad." ambivalently.'
>She said; "Not too bad." ambivalently.

//Wrongo. Unmatched quote.
>>'lol"
>SyntaxError: unterminated string literal:

We need to operate on our values.

What does + look like to you? That sure is what it does to numbers.

>>1 + 1
>2
>>1 + 2
>3
>>1 + 2 + 3
>6

What if we asked + to operate on Strings? Immaterial of what you thought, JS joins the strings. (String concatenation).

>>"Creativity" + "Lack"
>CreativityLack

Now I’m sure you’d be thinking of asking + to operate on a string and a number just for the laugh. Good job bonus points for that. If you didn’t, maybe it’s time you started because if there’s anything that I’d rather you leave with from this is the sense of curiosity. That is essential. Cultivate it if you think you don’t have enough of it.

I’m sure the curious among you are busy in playful discovery. All is very well.

If both the operands (values on which the operator operates on) of the + operator are not numbers, JS converts those values to string and concatenates them.

Aside: This is called operator overloading. The creators of JS decided in an ad hoc manner that + should do arithmetic as well as string concatenation. The conversion of a value to a string is an example of type coercion. (A value is coerced to a value of some other type to satisfy some implied computation)

>> 1 + "shoe"
>1shoe
>>"1" + '2' //neither are numbers because they're flanked by quotes.
>12
>>"1" + 2 + 3
>123
>>1 + 2 + "3"
>33          //WT..?

As for the somewhat unexpected turn of events in the last output, let me introduce you to associativity: The rule that resolves order of operation in a sequence of operations.

Consider this, line up a group of your friends facing your, ask them to turn 90 degrees left (their right), spread their arms, hold the respective wrists of the person in front and hug simultaneously. What you get is a left associative order. There are other ways to demonstrate this, but hugging is a sort of association. I think this imagery sticks better. Now if they did it in to the right (their left). We’d have a right associative arrangement.

So you see, + is left associative. In the case of "1" + 2 + 3, 2 is hugging "1". 3 is hugging both 2 and "1". Therefore "1" + 2 evaluates to the string "12" and next operation becomes "12" + 3 which is "123".

Now I’m sure you see why 1 + 2 + "3" evaluates to "33". We can override associativity by grouping using parenthesis.

>>1 + (2 + "3")
>123

If in doubt, always, make your intention explicit with parenthesis. Tiny bridge we just crossed there. Good job.

Summary.

  • Playful curiosity is a good thing.
  • Hug your family, friends and strangers.
  • REPL: Read Eval Print Loop. <- This

Understanding JavaScript.

January 15, 2010
js and html.

JS and HTML in the Works in the Web Browser.

It’s considered bad form to induce fear of the topic before a discourse. But what the heck, let’s just relax, visualize a cool sunny morning with birds chirping and flowers dancing in the breeze and move on.

JavaScript (JS) is not an easy first programming language to learn. There are many reasons why this is so. Take for instance the name “JavaScript”. The impression is that it’s like Java but perhaps a bit lighter. In the course of our discussion we’ll see why nothing could be further than the truth. Even if you don’t know Java or programming for that matter, you’d be misled. If first impression are thus, what hope if any is left? Another reason could be attributed to the schizophrenic environments (Eg: the web-browser) where JavaScript is usually imprisoned. Couple that with some blunders made by the designers of the language and you get what appears to be a soul sucking supernatural parasite.

But all of the above are only significant problems (perhaps the only problems) if you’ve made the wrong start – if you’re building upon misunderstandings, wrong notions and blind unguided explorations, the vast coldness of internet and the fiery depths of hell awaits you. :p Again, terrifying imagery and panic inducing facts. But remember, it’s all in our head. The sun is still there, the birds are still chirping and we’re moving along quite fine.

JS works in.

  • The browser: All modern browsers.
  • The server: Many projects under the umbrella term Server Side JS (SSJS).
  • As scripting languages for many applications. Adobe Photoshop, AfterEffects, The Java Virtual Machine et al.

What is this about?

Its about the octopus. (Refer the main image).

Although setting up your snazzy new website may be your prime concern and the ultimate goal of our meeting, we will sadly not be concentrating on such pragmatic issues for the want of making you self sufficient. For that want of giving you the safety boots and goggles required to pioneer this hazardous landscape of the octopus.

Thus this is also not about the famous close friends of JS: CSS and HTML. It is also hence not really about web development per se.

What you wouldn’t hurt to know

A vague Idea of what programming is about would help. So would your general ability to find your way around these technological contraptions that are the bane of our times.

What you need.

If you’re on Windows, you will require the Mozilla Firefox Browser and the Firebug plugin. Remember that beyond the function as a host for JS, we aren’t concerned with the Browser.

On GNU/Linux, you could either go with Firefox and Firebug or install the standalone JS interpreter spidermonkey. On Ubuntu

sudo aptitude install spidermonkey-bin && js 

will install and run the interpreter.

Firebug screenshot.

Hello world says Firebug.

The setup.

Once Firebug is installed and Firefox restarted, click the bug icon on the lower right of the window. Click the console tab on the window that pops up, click the red up arrow icon above the firebug icon to get a larger console.

Enter console.log("Hello wonderful world!"); and click Run. Note that “console” is a firebug object. It is not native JavaScript. We hope to steer clear away from such non native stuff in the spirit of our discourse but we need the console object to print things under firebug. You could also use alert("Hello world!") and in the case of our friends -all good people- who decided to use the standalone spidermonkey interpreter print("Hello kind world!");

Summary.

That’s all the foreplay folks. We get into the thick of things in the next post. Until then, consider these.

  • To excel in JS, start learning it in isolation.
  • JS is ubiquitous. It’s everywhere and it’s set to take over your world.
  • Wrong starts are almost invariably fatal.
  • Above everything, JS is extremely pleasurable and rewarding if approached correctly.

Hello world!

January 14, 2010

Hello folks. This is my first blog post. I’ll be blogging mostly around ‘light’ programming and assorted computing stuff. My first few posts will be on the JavaScript programming language. Then I hope to diversify to topics such as CSS, Processing, perhaps some Pseudo-Philosophy etc.

Wish me luck. 😛


Create your own website, free on WordPress.com.Create your own website.
Start free