JavaScript For Regular Guys (Part 1)

Introduction

So, JavaScript. That thing that makes AJAX, dynamic HTML and other fancy stuff possible. We know it exists somewhere deep on the browser. But what is it exactly? How does it work anyways? And even more important: How in the world do you even code for it?

Okay, reader. If you have any of those questions, today is your lucky day. We are going to find out the answers for them.

Some Background

Like every exciting article, we will be starting with some history. So, JavaScript was born with Netscape browsers about 18 years ago. It was first shipped with Netscape version 2 as a feature that would allow web pages to run scripted content on the browser right in the user computer. Its original name was Mocha, then it changed to LiveScript and finally ended up as JavaScript (JS). Wow, that’s what I call name evolution.

How Does It Work?

JavaScript is contained either on individual *.js files that are referenced by the web page or one or more inline HTML <script> blocks coded deep inside the HTML structure. The browser then interprets (that’s right, JavaScript is an interpreted language) all code on referenced files and <script> blocks by using its own JavaScript runtime and executes the code in the web page when load is complete.

To include JS files on a web page we would have to add <src="../file.js" /> tags for each file. The other way is to include JavaScript code inline inside a script block:

<script type="text/javascript" language="text/javascript">
    function doSomething() {
        alert("Something happened!");
    }
</script>

It is recommended that these blocks are right after the last HTML tag before the <body> tag on the page to improve loading times. Always remember that JavaScript is a functional scripting language. It executes all code in a file or script block from top to bottom sequentially. For example, the script above won’t do anything since we are never calling the function anywhere. So, we would have to do something like:

<script type="text/javascript" language="text/javascript">
    function doSomething() {
        alert("Something happened!");
    }

    doSomething();
</script>

The Domain Object Model (DOM)

JavaScript goes tight with the HTML structure of the page it is executed on. JavaScript sees all the HTML document structure as an HTML element tree called the DOM. This allows us to manipulate the document structure on runtime by referencing its DOM elements and change things as needed. For example, to change color of a paragraph 2 seconds after the page has loaded, we can use the following code:


<p id="target">Test paragraph...</p>

<script type="text/javascript" language="text/javascript">
    setTimeout(function() {
        var target = document.getElementById('target');
        target.style.color = '#00FF00';
    }, 2000);
</script>

By examining the previous code, we can see the use of the setTimeout function. JavaScript comes with a set of pre-defined global functions that don’t come from any object. They just can be used anywhere. No, literally ANYWHERE. If you come from a formal language like C# or Java, you know that, at some point, you’ll need to include namespaces or packages so your code can use things defined somewhere else. Yeah well, with JavaScript this is not the case. Global functions are auto-magically imported by the browser itself.

In the case of the setTimeout function, it takes two parameters: the first is a function that will execute after a specified amount of milliseconds; specified by the second parameter. The function we specified as the first parameter is what we know as an “anonymous function”. We call it “anonymous” because it has no name. Really? Yes, really. But you can assign a name to it if you want:

<script type="text/javascript" language="text/javascript">
    function colorChanger() {
        var target = document.getElementById('target');
        target.style.color = '#00FF00';
    };

    setTimeout(colorChanger, 2000);
</script>

It now has a name. But we can still use it as a variable and pass it as first parameter of the setTimeout function. Dammit, JavaScript!

Anyways, we slipped a little from the whole DOM topic. The important thing you gotta remember is that the global document variable can be used to retrieve HTML elements by ID (you already got the idea of what the DOM is all about). After we have the element on a JavaScript variable, we can change its attributes, move it somewhere else on the tree or even just delete the crap out of it à la Godfather.

JavaScript Has No Class

Even tough JavaScript is one of the most popular and used languages in the world, is not anything close to any other language you might have seen before. It is functional, dynamic weakly-typed and totally random at some points. Is like taking all programming languages known to mankind and mash them together in one single surprise-pack. Seriously, it gets a little crazy sometimes.

For instance, even though it has weakly-typed dynamic variables and other sorts of neat things, it has no formal way of defining classes. However, as the languages evolved from old computers into 21st century, a way to do something like Object-oriented Programming had to be on JavaScript by its first release. So, guys at ECMA had a dialogue, at some point while writing the first language specification, back in year 97′, that goes a little something like this:

  • Dude 1: “Dude, JavaScript is cool so far and everything but everyone is using something called Object-oriented something something.”
  • Dude 2: “Damn, kids these days. Let’s just allow functions to contain variables and other functions. Voilà. We got classes.”
  • Dude 1: “That sounds like is going to confuse lots of people… D:”
  • Dude 2: “Meh. Not really.”
  • Dude 1: “But…”
  • Dude 2: “NOT REALLY, I SAID!”

Okay maybe it was not like that but, since then, we have like four or five different ways to define something like classes. The one I like the most is as follows:

<script type="text/javascript" language="text/javascript">
    function CarFactory() {
        var carsProduced = 0; // Private variable

        this.name = 'Car Factory'; // Public variable

        this.getCarsProduced = new function() { // Public getter
            return carsProduced;
        };

        this.createCar = function() { // Public function
            showCarProductionMessage();
            carsProduced++;
        };

        function showCarProductionMessage() { // Private function
            alert("A car was produced.");
        };
    }

    var carFactory = new CarFactory();

    alert("Factory name: " + carFactory.name);

    carFactory.createCar();

    alert("Cars produced so far: " + carFactory.getCarsProduced());
</script>

How pretty does that looks? So, a function can also be a class definition with private members and all, just like any object-oriented language. This is known as prototyping.

Hopefully, the example is clear enough. I have a couple of things to clarify though. JavaScript, while trying to be object-oriented, is still a scripted language; never forget that. So, if you put the class definition after you use it, you’ll get a nice error complaining about the use of an undefined type since the interpreter has not yet seen the class prototype definition as it is after the code trying to use it. Also, look at the use of the keyword this. Things are just starting to get more and more interesting for sure.

The “this” Keyword

If you have worked with classes before, surely you’ll recognize the this keyword. This magical keyword often refers to the class where the current method using it is defined. Well, in JavaScript (once again screwing up with our brains) the this keyword refers to the function owner and can refer to several things depending on the scope it is used:

This Keyword Scope Conventions

Now you see how tightly coupled JavaScript is with the DOM tree. The default owner for all scripts is the global window DOM element.

Now, you can see the last two usages in the table involve the use of the call() and apply() functions. These functions are useful if we would like to change the value this refers to. That would be your homework: Check the use of call() and apply().

Conclusion

So, we have reviewed how JavaScript was conceived and how it is structured. This is essential in order to understand more complex examples like DOM element events and asynchronous server calls and of course– server-side JavaScript; which we will be examining with more care on future articles.

Stay tuned! ;)

5 thoughts on “JavaScript For Regular Guys (Part 1)

  1. I have the impression that Brendan Eich will have difficulty agreeing with you regarding your description of the inception of JavaScript. I am pretty sure Brendan Eich was quite familiar with object-orientation by the time he created JavaScript. It is my understanding that Eich actually wanted to put Scheme in the browser, but people from Netscape wanted it to look like Java. In an interview for the book Coders at Work, Eich mentions that he got a lot of influence from the Self programming language, which is also an object-oriented, prototype-based programming language and from Smalltalk which is also object-oriented.

    • Oh no, no, no… I would never dare to question mr. Eich’s knowledge of the object oriented paradigm. I just wanted to emphasize in the fact that JS is a crazy language in all aspects. Actually, you’re not the first one to take it that way. I think I’ll end up editing it to avoid confusion. :/

      • I see your point now. In that case I believe a post on the differences between prototype-based object-orientation vs. class-based object orientation would be really, really cool. Above all because the first is less common and perhaps that what makes you suggest that JavaScript is a crazy language. I have to mentioned as well, that I have had difficulty putting myself on the shoes of the “regular guy”. I mean, what do the “regular guy” would like to know about JavaScript? I know very little JavaScript, just enough to survive in a web-based project, so I guess I should be a regular guy. And as I regular guy I believe I would have prefered individual posts about everyone of these topics, that way I could focus on what I am looking for instead of a set of random facts about the language. It could be interesting to focus on the language alone, irrespective of its browser-based nature, that is the beauty of the language itself. Another interesting aspect that I know is less familiar JavaScript in the server-side, what about node.js. An article about that would be really cool as well.

      • You’re right about that, Ed. Actually this is part 1 of a series of articles. Is a really really general view of Javascript. I wanted to start from its very original form (browser intended) evolving to new trends such as server-side JavaScript like Node in order to keep a fluent pace through the language roadmap.

        For me “the regular guy” is someone with general object-oriented knowledge. That’s why I say is “crazy”. Back then when I started learning JavaScript tha was my first reaction; I was really confused about a lot of things since it was not close to anything I have seen in languages like Java or C#; let alone prototyping.

        Rest assured I’ll have your topic suggestions in mind for future articles. Hope to have your always-constructive feedback on those as well. :)

  2. Keep them coming, Luis. You know that I read all your articles and often try whatever code examples you write. For me it is important to share everything you learn. Some may agree with you, some may not agree, that is always the case. In any case the beauty of this is to have other bloggers or readers who leave us comments and enrich our knowledge and understanding of the topics. Also a fresh perspective of a good reader usually can help to improve an article. Like when you said that certain part of the article was being misinterpreted, that gives you hint of how to improve the article for future readers. And you and I are both to this world of blogging, I am sure we both we’ll have to learn a few lessons along the way :-)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s