ARTICLES

VIDEOS

BOOKS

FORUM

Introduction to JavaScript

by kirupa   |   filed under JavaScript 101

HTML is all about structure and content. CSS is all about making things look good. Between the both of them, you can create some pretty nifty looking things:

Despite the niftiness of how 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 have a certain level of interactivity and personalization that goes well beyond what HTML and CSS by themselves can provide:

example of sites that use JS a lot

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

Onwards!

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:

  1. Listen to events like a mouse click and do something.
  2. Modify the HTML and CSS of your page after the page has loaded.
  3. Make things move around the screen in interesting ways.
  4. Create awesome games that work in the browser like Cut the Rope.
  5. Communicate data between the server and the browser.
  6. 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. Below is an example of 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 like function, if, else, alert, name, etc. 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 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.

OMG! A JavaScript Book Written by Kirupa?!!

To kick your JavaScript skills into outer space, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.

BUY ON AMAZON

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.

Basic Web Development Functionality Needed

To start writing JavaScript, you do 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 tutorial. 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. Once 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 following screenshot:

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 double click on hello_world.htm. You will see your default browser appearing and displaying the contents of this file. You should see something that looks like the following:

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 towards 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 that looks as follows appear:

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

What you just did is write 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 as 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 3rd 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 bowels of our 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 a quotation mark:

<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 explore JavaScript further. We'll look at strings in greater detail shortly, so 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:

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 if your favorite TV show happens to involve the day-to-day lives of the Kardashians...or meerkats.

Conclusion

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.

Up Next: Variables

Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you'll ever run into will be happy to help you out!

When Kirupa isn’t busy writing about himself in 3rd person, he is practicing social distancing…even on his Twitter, Facebook, and LinkedIn profiles.

Hit Subscribe to get cool tips, tricks, selfies, and more personally hand-delivered to your inbox.

COMMENTS

Serving you freshly baked content since 1998!
Killer hosting by (mt) mediatemple

Twitter Youtube Facebook Pinterest Instagram Github