Hola Mundo – An Intro to Javascript

All real-world languages have many ways of saying the same thing– Hiya doin, Hello, What’s up? The same is true of the programming language JavaScript. Let’s look at different ways of saying “hello world” as a way of learning to code with JavaScript.

Open up a new plain text file in Notepad, and paste or type the following HTML page content into it:

<!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;>
<html>
  <head>
    <meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot;>
    <title></title>
    <script type=&quot;text/javascript&quot;>
      function sayHello (){
        alert (&quot;hola mundo!&quot;)
      }
      function sayHello2 (){
        var s = prompt(&quot;Enter your name:&quot;, &quot;John Q. Public&quot;);
        alert (&quot;hola mundo! and &quot; + s);
      }
      function sayHello3 (){
        // This is a callback for the keyup event on a text box
        // it dynamically updates a heading1 in the document with the text box's value
        var src = document.getElementById(&quot;obSource&quot;);
        var out = document.getElementById(&quot;idHeading&quot;);
        out.childNodes[0].data = src.value;
      }
    </script>
  </head>
  <body>
    <div>
      <input type=&quot;button&quot;  value=&quot;click me&quot; onclick=&quot;sayHello();&quot; >
      <P>&amp;nbsp;</P>
      <hr>
      <input type=&quot;button&quot;  value=&quot;click me&quot; onclick=&quot;sayHello2();&quot; >
      <P>&amp;nbsp;</P>
      <hr>
      <input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >
      <P>&amp;nbsp;</P>
    </div>
    <div>
      <hr>
      <h1 style=&quot;font-family:verdana&quot; id=&quot;idHeading&quot;>A Sample Heading</h1>
    </div>
    <hr>
  </body>
</html>

Save the page to your desktop as “holaMundo.htm,” and double-click it to load it into your browser. Press the first button to make the greeting appear.

The first button: an output statement

Focus on just this portion of the code:

function sayHello (){
  alert ("hola mundo!")
}

It’s pretty clear, even if you have no programming experience, which statement is actually outputting the message: the alert statement. But what’s the other stuff surrounding that statement?

The function statement wraps the alert function in a code block that makes it easy to chunk up a big program. You can think of functions as being like the chapters of a good novel: they break up the action into mini stories that make it easy for the reader to read the whole story.

We could put more program code before or after the alert statement, but don’t need to if we just want to illustrate how the alert statement works. Other functions in our example code do hold several statements.

The second button: an input statement

Reload the example page in your browser and press the second button this time. Respond to the prompt, press OK, and watch the new message appear.

Let’s study just this much of the main program:

function sayHello2 (){
  var s = prompt("Enter your name:", "John Q. Public");
  alert ("hola mundo! and " + s);
}

The prompt statement takes in text from the user of your JavaScript program. The first _parameter_ is the message to give the user, and the second is the text that the prompt statement will return with if the user enters no text.

JavaScript variables

Notice the program code to the left of the prompt statement: “var s =”. This code creates a variable–space from your computer’s memory–to hold the text that the prompt statement gets from the user. There are different kinds of variables for different data types: some variables hold string values, e.g. “hola!” while others hold numeric values e.g. 3.1415927, 77.

JavaScript programming can be a bit frustrating at times because, no matter what type of data a variable is holding, all variables are declared with just the “var” keyword. Compare this with Java programming, where you tell the compiler the specific type of data that a variable holds, for example:

  • int a;
  • String s;

The plus operator

Notice the line after the prompt statement. It’s an alert statement with a plus operator inside it. The plus operator joins two strings together: the literal string “Enter your name,” and the string held in the variable s. Think of one string being added to another, as on number is added to another, and the plus operator will make sense to you.

The text box

Reload the sample program in your browser and enter some text in the text box. Notice that the headline echoes the text you enter with each keystroke.

Focus on just the third function in your program:

function sayHello3 (){
  // This will be a callback for the key up event on a text box
  // It dynamically updates a heading1 in the document with the text box's value
  var src = document.getElementById("obSource");
  var out = document.getElementById("idHeading");
  out.childNodes[0].data = src.value;
}

How “sayHello3″ works

The first two statements are declaring and making assignments to variables. Two _object references_ are stored in the variables. The objects represent elements of the HTML page. One object is the text box that you type into:

<input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >

Notice the id _attribute_ for this element: “obSource.” This attribute value is the name that the program code in sayHello3 uses to access the text in the text box. This functionality is just like calling someone on the phone: you can’t call a particular person unless you have her phone number. The id attribute is like the phone number we use to “call” or get access to the text box element.

In the same way, the “var out” statement gets a reference to the destination object to receive the user-input text.

The script’s data structure: a tree

The last statement in sayHello3 copies the source text to the destination. Although this statement looks a bit cryptic, it will make a lot more sense if you see the data structure being used here: it’s a tree, whose leaves are referred to as “nodes.”

We’ve talked about the _what_ of the program but have missed the _when_ so far. It’s pretty striking that the page’s heading changes dynamically with each keystroke in the text box. How does the program code make that happen?

When the sayHello functions are called: events

The answer is events, and subscribing to, or listening to those events. The event that concerns this example program is the keyup event on the text box control. When that event happens, the browser calls the sayHello3 function.

How does the browser know which function to call? The HTML markup tells it:

<input type=&quot;text&quot; id=&quot;obSource&quot; value=&quot;type something&quot; onkeyup=&quot;sayHello3();&quot; >

The key attribute here is “onkeyup.” Look at what’s assigned to it: sayHello3. That assignment tells the browser to call sayHello3 when a key up event happens to or on the text box.

Approaches to Learning JavaScript

Two of the best ways of learning how to code in JavaScript are these: tinker with and take apart existing working scripts, and memorizing and recreating a working script without consulting resources beyond your gray matter.

Continue your JavaScript learning journey by tinkering with the code in this tutorial.

References

JavaScript Core Reference: http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/reference/contents.html

Got something to say? Go for it!