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 weather example you can see in at http://bit.ly/kirupaWeather. Figure 1.1 shows what this weather example looks like.

Image

FIGURE 1.1

A colorful weather example highlighting a 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 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. In a nutshell, it allows you to add interactivity to your document. A short list of things you can do with JavaScript include:

  • 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 that work in the browser like Cut the Rope.

  • Communicate data between the server and the browser.

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

....and 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. The following example shows some old-fashioned, fresh outta-the-oven JavaScript:

let defaultName = "JavaScript";

function sayHello(name) {
  if (name == null) {
    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 such as function, if, else, alert, name. 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 really soon, and you’ll also 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 behind making it work, I’m not going to bore you with stuff like that. Instead, I want you to get your hands dirty by writing some JavaScript. By the end of this tutorial, I want you to have created something sweet and simple that displays some text in your browser.

Hello, World!

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. Let’s get started.

Image Tip

Basic Web Development Familiarity Needed To start writing JavaScript, you need to have basic familiarity with building a web page, using a code editor, and adding some HTML and CSS. If you aren’t too familiar with the basics around this, I encourage you to first read the Building Your First Web Page chapter. That will set you up nicely for what you’ll be seeing next.

The HTML Document

The first thing you need is an HTML document. This document will host the JavaScript that you will be writing. Launch your favorite code editor. If you don’t have one, I encourage you to use Visual Studio Code. After you’ve launched your favorite code editor, go ahead and create a new file. In Visual Studio Code, you will see a tab that says Untitled similar to the screenshot in Figure 1.3.

Image

FIGURE 1.3

Untitled-1 tab in Visual Studio Code.

Save this newly created file by going to File | Save. You will be asked to give this file a name and specify where you would like to save it. Give this file the name hello_world.htm and save it to your Desktop. After you have saved this file, add the following HTML into it:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>An Interesting Title Goes Here</title>

  <style>

  </style>
</head>

<body>
  <script>

  </script>

</body>

</html>

After you’ve added this HTML, save your document to confirm these changes. It’s time to take a look at what our page looks like in our browser.

In either File Explorer or Finder, navigate to your Desktop folder and double-click on hello_world.htm. You will see your default browser appearing and displaying the name of this file. You should see something that looks like what is shown in Figure 1.4.

Image

FIGURE 1.4

Titled tab in Visual Studio Code.

If everything worked out well, you should see a blank page! No, there isn’t anything wrong here. While our page has content, there is nothing visible going on. That’s fine, for we’ll fix that shortly. The key to making this fix is to go back to your code editor and focus on the <script> tag that you see toward the bottom of your HTML:

<script>

</script>

The script tag acts as a container where you can place any JavaScript you want to run inside it. What we want to do is display the words hello, world! in a dialog that appears when you load your HTML page. To make this happen, inside your script region, add the following line:

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

Save your HTML file and run it in your browser. Notice what you will see once your page has loaded. You should see a dialog appear that looks like Figure 1.5.

Image

FIGURE 1.5

Your hello world dialog box should look like this.

If this is your first attempt at writing JavaScript, congratulations! Now, let’s look at what you just did.

Looking at the Code: Statements and Functions

You just wrote a very simple JavaScript statement. A statement is a 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!");

You can tell something is a statement by looking at the last character in it. It is usually a semicolon (;) just like what you see here.

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. It is responsible for getting your attention by displaying some text.

To be more precise, the word alert is something known as a function. You will use functions all the time; 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 with a message you pass to it lives deep inside the 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!, and notice how I am specifying it. I wrap the words inside quote marks:

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

Whenever you are dealing with text (more commonly known as strings) you will always wrap them inside a single quote or a double quote. 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 further explore JavaScript. We’ll look at strings in greater detail shortly; for now, just enjoy the view.

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

<script>
  alert("Kirupa Chinnathambi!");
</script>

If you run your application, you will see your name appear in the dialog (Figure 1.6).

Image

FIGURE 1.6

The dialog box now displays your name.

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.

The Absolute Minimum

In this tutorial, you created a simple example that helped get you familiar with writing some JavaScript code. As part of getting you familiar, I threw a lot of concepts and terms at you. I certainly don’t expect you to know or remember all of them now. In future tutorials, we are going to pick each interesting part of what you’ve seen so far and elaborate on it in more detail. After all, I’m pretty sure you want to eventually do things in JavaScript that go beyond displaying some text in a ridiculously annoying way using a dialog box.

Going forward, at the end of each chapter, you may even see a set of links to external resources written by me or others. These resources will give you more details or a different perspective on what you learned, along with opportunities to put your learning into practice with more involved examples. Think of what you see in this book as a jumping-off point for greater and more awesome things.

If you have any questions on the content here, post on the forums at https://forum.kirupa.com for really quick help from both me as well as some of the web’s coolest developers.

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

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