JavaScript 101: Hello World!

JavaScript is a programming language that web browsers understand. You can use it to make your web pages interactive by:

  • Responding to user actions and changes on the page
  • Manipulating the web page’s contents and behaviour
  • Communicating with the user directly

You can do just about anything you want with a web page, using JavaScript.

In this introductory tutorial and the series to follow, I’ll introduce the JavaScript language and how to write it, through a series of practical worked examples.

Example 1: Hello World!

“Hello World!” is traditionally the first thing you learn to do with any new language.

What we want to do

When the user clicks a button, show the message, “Hello World!”.

Step 1: Create a button

Our web page needs a button to click:

<input type="button" id="hello-world" value="Hello" />

Let’s explain the various bits of the HTML:

input
This is the generic HTML command for a form input. (Note it’s self-closing, so if you’re coding xHTML you must use the trailing slash.)
type=”button”
There are several types of input in HTML: button, text, submit-button.
id=”hello-world”
We don’t actually need this yet, but it’s good practice to give every important element on your page its own useful ID (unique identifier).
value=”Hello”
With a button, the value parameter sets the text that’s displayed on the button.

Try clicking the button…

Did anything happen? No? Good.

This is exactly right, because we haven’t told the page that anything should happen when the button is clicked. Let’s look at ways of making something happen when the button is clicked.

Making something happen with inline JavaScript

The easiest way is to write what we want to happen into the button tag itself. For example…

<input type="button" id="hello-world2" value="Hello" onClick="alert('Hello World!');" />

Try it now. (If nothing happens, check that JavaScript is enabled in your browser.)

(Note that I’ve given this button the id “hello-world2″, because every id on the page must be unique, and I already have a button with the id “hello-world” above.)

Let’s look in detail at what this bit of code is saying:

onClick=”"
onClick is an event handler. It tells the browser to run whatever’s in the quotes when the event “click” happens to the button.
alert()
alert() is the first JavaScript function we’ve seen. It’s built into JavaScript, and in a web browser it shows an alert box on the screen.
‘Hello World!’
You notice that alert(), like all function calls, is followed by a pair of round brackets. Some functions expect to be given parameters – extra information that the function needs. The alert() function takes one parameter – the message you want to display. This message has to be put inside quotes (either single- or double-quotes), so that JavaScript knows just to treat it as a piece of text. because we’ve already got the whole bit of JavaScript inside double-quotes (onClick=”…”), I’ve used single-quotes here.
;
The semicolon after the alert function tells the browser that it’s the end of the statement. It’s not strictly required, but if you wanted more than one thing to happen, you’d separate the statements with semicolons.

Problems with inline JavaScript

I’ve shown you how to write your instructions inline (i.e. in your HTML), because it’s the easiest and quickest way. However it’s not very good practice, because (just like the problems with inline CSS):

  1. You have to write your code out in full for every button. (OK, this example is very very simple, but it could be much more complicated.)
  2. That means that if you have more than one button that does this function, and you want to change what happens, you have to locate and edit every occurrence of the code).
  3. It makes your pages longer, more cluttered and more complex.

A better way to manage your code is to put it in separate functions, which, just like CSS again, can be written either:

  • into the page header (or body, but header is best)
  • or in separate files

Making something happen with a custom function

To do the same thing as we’ve achieved above, but with neater code, we’ll write our own JavaScript function.

First thing is to write a block of JavaScript in the <head> section of our HTML page.

<head>
<script type="text/javascript">
<!--
   function helloWorld() {
      alert('Hello World!') ;
   }
 // -->
</script>
</head>

Note that the script type= stuff above is a common block that you’ll always use to write blocks of JavaScript into your web pages. I do explain what it does below, but it’s not vital that you understand it now.

JavaScript code

<script type=”text/javascript”> … </script>
The <script> tag tells the browser that some client-side script follows, and where it ends. The type parameter tells the browser what kind of script it is, so the browser knows to use its JavaScript capability to interpret the code.
<!– … //–>
This is an HTML comment. It prevents whatever’s between the comment start & end tags from being displayed on screen. The last line has a JavaScript comment (//) in front of it, to tell the JavaScript block to ignore that line.
function
function is saying that we’re creating a new custom function here
helloWorld()
helloWorld is its name. The pair of round brackets () follows all function definitions. This is where you may tell a function what parameters to expect to be given. We don’t have any parameters in this example, so we have empty brackets.
{ … }
Everything between the curly braces { } is the body of the function. This is the code that gets run when you call the function.
alert(‘Hello World!’);
This is exactly what we had before inside our onClick() event handler. Now, it’s stored in the document <head> section.

Firing the function

To fire the function, we’ll change the bit of code inside the onClick() event handler as follows.

<input type="button" id="hello-world2" value="Hello" onClick="helloWorld();" />

Now, instead of alert() function, we’ve written the name of our own custom function.

When the button is clicked, the browser will look within the page (and any referenced JavaScript files) for a function of that name. We’ve already written a function of that name in our <head> section, so the browser runs that function.

The benefit of this approach to writing JavaScript code is, if we want to change what happens when the “Hello” button is clicked (say, we want to ask the user their name, and then say “Hello Bob!”, we change it in only one place.

Making something happen with an external JavaScript file

This is fairly straightforward change, which gives us even more benefits.

Instead of writing our JavaScript code into a block in the document <head>, we write it into a separate file, which we include in any pages that might use its functions.

hello.js

You’d write the following code into a separate file, and save it as “hello.js” (you can call it whatever you want).

function helloWorld() {
   alert('Hello World!') ;
}

Include the external js file in your document <head>

<head>
   <script type="text/javascript" language="javascript" src="hello.js"></script>
</head>

Again, this uses the <script>…</script> HTML tag, but instead of writing our code between the start and end tags, we tell the browser that the script is in another file whose “source” (src) is “hello.js”.

This will have exactly the same effect as the previous 2 methods we’ve tried, but is much better because now:

It’s easier to update our code. If we want to change what the helloWorld() function does, we only have to change it in one place, and those changes will be reflected in all pages that include the hello.js file.

It’s easier to manage our code. If you come back to a web site project, it’s much easier to find out what’s doing what if your styles (CSS) and functions (JavaScript) are kept separate from your content (HTML). These benefits increase as sites get more complex.

The browser should only have to download your JavaScript code once, no matter how how many pages use it, because it can cache (i.e. remember) the external file.

(Note, if you’re using xHTML, the language parameter is not allowed, just use the type parameter in your <script> tag.)

33 Comments Leave a comment

  1. Maxime De Greve says:

    This basics are really great for someone that just started getting into Javascript! Great article!

  2. 13andincrediblycut says:

    I could’ve wrote a more descriptive article and I’m only 13! :X

    • Ben Hunt says:

      Hi. I’d definitely advise you to write your own articles. Get blogging and share your knowledge with the world. (But keep an eye on your grammar; e.g. it’s “written”, not “wrote”.)

    • Bicho says:

      OWNED.

      That is all.

  3. Darryl says:

    I thought this information was very informative and straight forward. Thanks for taking the time to explain each of your steps.

    Darryl

  4. jojo says:

    Is it possible to get some data back from the function?

    • Juan says:

      Just use return keyword followed by whatever you want to return from the function.

  5. Rob says:

    Great article! I’m a Java programmer, but I’m brand new to Javascript this was a great introduction. I just wish there were more articles? JS102, 103, 201, and so on. Can you point me to a good resource for more info? Rob

  6. Pingback: Becoming a javascript Guru. Episodio 1 ( To Do List ) - .Labs

  7. Angela S. says:

    I thought the information in this article was very informative and very easy to understand for a beginner. Great job!

  8. jcanini says:

    Stumbled on this, great article. Thanks

  9. Andrew says:

    Also stumbled on this, interesting read!

  10. stubborn says:

    Hello. I have a problem. I would like to run onclick event for a button in other javascript file, not to put inside of input tag, i mean:

    index.html

    example.js

    document.getElementById(“pincha”).onclick = show();

    function show(){
    alert(“got it!”);
    }

    something like this, but i dont know how. How would you do it?

  11. Chris says:

    Great article .. I’ve just read few of your articles and it really a great site for a beginner like me..

  12. Zach says:

    this was very helpful, its hard to find this well put together of an article.
    do you have any more tutorials?

  13. sheeba says:

    thanks a lot sir for helping us:-)

  14. sheeba says:

    its very much helping

  15. Bored says:

    “/&gt” (or />) is NOT valid HTML.
    XHTML uses these, and ONLY XHTML (they do not exist in HTML.)

    Let’s say

    What happens is the parser reads
    “>> “new element”
    “br” >>> “tag name br”
    “/” >>> “unexpected parameter ‘/’: ignoring”
    “>” >>> “end tag”

    Just to further explain, “/>” is a self closure, if HTML supported it in any way what-so-ever then:

    Should be valid (in XHTML it is, HTML it is not).

    Instead, HTML supports “rule based closures.”

    So let’s say
    hellogoodbye

    li’s rule says that a li element cannot contain another li; hence it will automatically close the index.

    But let’s say something else:
    hellogoodbye

    P’s rule says that if there is no text between the tags that it will not render anything.

    Using self closeure, this should be valid:
    hellogoodbye

    Here, ‘/’ is viewed as a parameter and is ignored. the P tag terminates at the next block (li) and the rendering is different.

    I do not understand why people are insisting on using something that does not actually exist.

  16. Bored says:

    -___-

    <ul><li>hello<li>goodbye</ul>

    <ul><li><p></p>hello<li>goodbye</ul>

    <ul><li><p />hello<li>goodbye</ul>

  17. Bored says:

    Oh, I see… your site is written in XHTML hence you were mostly talking about XHTML.

    Still, XHTML and HTML are two very different beasts and while XHTML will do what you say or crash; HTML is a mess of rules and lax syntax.

    *We really should just abandon HTML; the few extra bytes for basic ‘HTML to XHTML’ can correct many issues of “browser specific rendering of improperly used tags.”

  18. Charlie says:

    This is great. I started with a completely blank slate, so anything more detailed/convoluted just throws me off. A great start to my javascript learning curve.

    Thanks.

  19. Pingback: The Relationship between HTML, CSS, and JavaScript | Weblog for MIS 4153

  20. libono says:

    it does not give me exactly what i wanted

  21. Rafe says:

    Very good explanation style!

    I’m trying to implement a Mayan long count display (first try @ js) but I get *Undefined* for results:

    function LZ(V){
    var R = (’0′ + V).slice(-2);
    return ‘:’ + R;
    }
    function Maya_Long(){ //1970Jan01=Mayan long count day 1856305
    // 144k 7200 360 20 1s – ‘digit’ weights (values)
    // 12 17 16 07 05 = 1856305
    var mD = new Date(); // Today’s date in mS since unix epoch
    // Divide by mS/day (86400000) to get days since 1970 then add Maya days
    var D = mD.valueOf()/86400000 + 1856305; // D=days since Mayan epoch

    var Baktun= (D/144000).ToInteger; D=D-Baktun*144000;
    var Katun = (D/7200).ToInteger; D=D-Katun*7200;
    var Tun = (D/360).ToInteger; D=D-Tun*360;
    var Uinal = (D/18).ToInteger;
    var Kin = D-Uinal*18;
    document.getElementById(‘Maya’).innerHTML = Baktun+LZ(Katun)+LZ(Tun)+LZ(Uinal)+LZ(Kin);
    }

  22. Rafe says:

    Re. the previous post, I solved it like this:

    function Lz(V){ return (’0′ + V).slice(-2); }
    function LZ(V){ return ‘:’ + Lz(V); }
    function Maya_Long(){//1970Jan01=Mayan long count day 1856305
    var mD = new Date();
    // Convert today’s date to days since 1970 then add Maya days
    var Kin = parseInt(mD.getTime()/86400000)+1856305;
    // Kin = days since Mayan epoch
    var Baktun = parseInt(Kin/144000); Kin=Kin-Baktun*144000;
    var Katun = parseInt(Kin/7200); Kin=Kin-Katun*7200;
    var Tun = parseInt(Kin/360); Kin=Kin-Tun*360;
    var Uinal = parseInt(Kin/18);
    Kin = Kin-Uinal*18;
    document.getElementById(‘Maya’).innerHTML = “ ”+Lz(Baktun)+LZ(Katun)+LZ(Tun)+LZ(Uinal)+LZ(Kin)+” “;
    }

  23. Bob says:

    Nice article! I have to start somewhere right… ;)

  24. Marian says:

    i want to be like you,how can i start my first step?and from where?i am computer student.

  25. mark cedric says:

    It’s luck but ok