1. Hello, World!


In This Chapter

Learn why JavaScript is awesome

Get your feet wet by creating a simple example

Preview what to expect in subsequent chapters


HTML is all about displaying things. CSS is all about making things look good. Between the both of them, you can create some pretty nifty-looking stuff like the examples you see on CSS Zen Garden (csszengarden.com). Figure 1.1 shows one such example.

Image

FIGURE 1.1 The CSS Zen Garden home page highlighting one layout designed entirely using only CSS.

Despite how nifty sites built using only CSS and HTML look, they will be pretty static. They don’t adapt or react to what you are doing. With those two, it’s almost like watching a rerun of a great Seinfeld episode over and over again. It’s fun for a while, but it gets boring eventually. The web today isn’t static. The sites that you use often (such as those in Figure 1.2) have a certain level of interactivity and personalization that goes well beyond what HTML and CSS by themselves can provide.

Image

FIGURE 1.2 Examples of various web sites that rely heavily on JavaScript for their proper functioning.

To make your content come alive, you will need some outside help. What you need is JavaScript!

What Is JavaScript?

JavaScript is a modern-day programming language that is a peer of HTML and CSS. To be a bit vague, it basically enables you to add interactivity to your document. A short list of things you can do with JavaScript include the following:

• Listen to events like a mouse click and do something.

• Modify the HTML and CSS of your page after the page has loaded.

• Make things move around the screen in interesting ways.

• Create awesome games (like “Cut the Rope”) that work in the browser.

• Communicate data between the server and the browser.

• Allow you to interact with a webcam, microphone, and other devices.

....and much MUCH more! The way you write JavaScript is pretty simple—sort of. You put together words that often resemble everyday English to tell your browser what to do. Here is an example:

var defaultName = "JavaScript";

function sayHello(name) {
    if (name === undefined) {
        alert("Hello, " + defaultName + "!");
    } else {
        alert("Hello, " + name + "!");
    }
}

Don’t worry if you don’t know what any of that means. Just pay attention to what the code looks like. Notice that you see a lot of English words like function, if, else, alert, name, and so on. In addition to the English words, you also have a lot of bizarre symbols and characters from the parts of your keyboard that you probably never notice. You’ll be noticing them plenty enough really soon, and you’ll fully understand what everything in this code does as well.

Anyway, that’s enough background information for now. While you would expect me to now provide a history of JavaScript and the people and companies that make it work, I’m not going to bore you with stuff like that. The only thing to know is that JavaScript is not related to Java. And with that, we’ve covered the relevant history that matters. Instead, I want you to get your hands dirty by writing some JavaScript. By the end of this chapter, you will have created something sweet and simple that displays some text in your browser.

A Simple Example

Right now, you may feel a bit unprepared to start writing some code. This is especially true if you aren’t all that familiar with programming in general. As you’ll soon find out, JavaScript isn’t nearly as annoying and complicated as it often pretends to be. It is simply just dull and boring. Big difference!

Code Editing Tools

Sorry to interrupt, but there is one more thing to call out before we go on. This entire book is written with no expectation that you use a fancy HTML authoring tool or a code editor. All you need is a basic editor (like Notepad!) that enables you to see HTML, CSS, and JavaScript. Now, that isn’t to say that you won’t be better off with a good code editor. They do make your life easier without taking away from the ruggedness of learning JavaScript with your bare hands.

Some of my favorite code editors are

• Atom

• Sublime Text

• Notepad++

• TextMate

• Coda

• Visual Studio Code

This book doesn’t cover how to work with any particular code editor, nor does it make a big deal out of it. As long as you know how to create a new document, make some edits, save the document, and preview it in a browser, you know everything you need to follow along.

If you are new to code editors and are unsure how to proceed, then check out my playlist of short videos that shows how to use many of the editors listed here to work with HTML, CSS, and JavaScript: http://www.kirupa.com/links/editors.htm.

The HTML Document

The first thing you need is an HTML document. This document will host the JavaScript that you will be writing. You can use any blank HTML document that you want, but if you don’t have an HTML page already created and/or want to follow closely along, create a blank HTML page and add the following content into it:

<!DOCTYPE html>
<html>

<head>
  <title>An Interesting Title Goes Here</title>

  <style>

  </style>
</head>

<body>

  <script>

  </script>
</body>

</html>

If you preview this document in your browser, you won’t really see anything. That is totally expected, for this is (after all) a blank document that has nothing really going on. That’s fine, for we’ll fix that shortly starting with the script tag that you see toward the bottom of your example:

<script>

</script>

The script tag acts as a container where you can place any JavaScript you want to run. What we want to do is display the words hello, world! in a dialog box that appears when you load your HTML page. Depending on what browser you are using, Figure 1.3 shows what such a dialog box would look like.

Image

FIGURE 1.3 Our dialog box displaying hello, world!

Inside your script region, add the following (highlighted) line:

<script>
  alert("hello, world!");

</script>

Save your HTML file and open it in your browser. Once your page has loaded, you should see a dialog box with the words hello, world! displayed. It should look very similar to the screenshot you see in Figure 1.3.

If this is your first attempt at writing JavaScript, congratulations! You just crossed a giant hurdle. You created a working example using it. Now, let’s look at what you did and try to make sense of what is going on.

Looking at the Code: Statements and Functions

What you just did is write a very simple JavaScript statement. A statement makes up the logical set of instructions that tell your browser what to do. A typical application will have many MANY statements. In our case, we just have one:

alert("hello, world!");


Image Note

You can usually tell when something is a statement by looking at the last character in it. It is usually a semicolon (;) just like what you see in the earlier code snippet. Now, this is isn’t a guaranteed way to identify a statement. JavaScript works fine in many cases without having a semicolon at the end of your statements, and some developers may even choose to omit them as part of the code they write.


Inside a statement, you will see all sorts of funky JavaScript jargon. Our code, despite being just one line, is no exception. You have this weird thing called alert that makes an appearance. This is an example of a common English word that behaves similarly in the JavaScript world to how it might in our everyday world. It is responsible for getting your attention by displaying some text.

To get more precise, the word alert is actually something known as a function. You will use functions all the time, for a function is basically a reusable chunk of code that does something. The something it does could be defined by you, defined by some third party library you are using, or it could be defined by the JavaScript framework itself. In our case, the code that gives your alert function the magical ability to display a dialog box with a message you pass to it lives deep inside the bowels of your browser. All you really need to know is that if you want to use the alert function, simply call it and pass in the text you want it to display. Everything else is taken care of for you.

Getting back to our example, the text you want to display is hello, world!. Notice how I am specifying it. I wrap the words inside quotation marks:

alert("hello, world!");

Whenever you are dealing with pieces of text (more commonly known as strings), you will always wrap them inside single or double quotation marks. I know that seems weird, but every programming language has its own quirks. This is one of the many quirks you will see as you explore JavaScript further. We’ll look at strings in greater detail shortly, so for now, just enjoy the view from the outside.

Let’s go one step further. Instead of displaying hello, world!, change the text you are displaying to show your first and last name instead. Here is an example of what my code looks like when I use my name—or the name I wish I had:

alert("Steve Holt!!!");

If you run your application, you will see your name appear in the dialog box. Pretty straightforward, right? You can replace the contents of your string with all sorts of stuff—the name of your pet, your favorite TV show, and so on. JavaScript will display it, and (best of all) it will not judge whether your favorite TV show happens to involve the day-to-day lives of the Kardashians...or meerkats.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.96.105