Lesson 2: Your First JavaScript

By Maria Antonietta Perna

Now that you know what JavaScript is and what you can do with it, it's time to get to the practical stuff.

In this lesson you are going to learn:

  • how to embed your JavaScript in the HTML page;
  • how to reference your JavaScript from a separate file;
  • how to comment your JavaScript code and why it is recommended;
  • how to create your first JavaScript-powered web page.

The HTML

To insert a JavaScript script in an HTML page, you use the <script> ... </script> tag. Don't forget the closing </script> tag! Now get ready to fire off your text editor of choice and let's get coding!

Let's start with a basic HTML page, like this one:

	  
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>

	  </head>
	  <body>

	  </body>
	  </html>
	  
	  

The JavaScript script is inserted either in the HTML page itself or in a separate file.

Embed JavaScript in the HTML page

The <script> tag and its type attribute tell the browser: "Hey, browser! There's a script coming up, and it's a JavaScript script."

You can do this either in the <head> section, as follows:

	  
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
		
      <script type="text/javascript">
	  //JavaScript code goes here
      </script>
		
	  </head>
	  <body>

	  </body>
	  </html>
	  
	  

Or or at the very bottom of the document just before the closing </body> tag, like so:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
	  </head>
	  <body>
        
      <script type="text/javascript">
      //JavaScript code goes here
      </script>
		
	  </body>
	  </html>
	  
	  

If you're wondering whether it's best to place your <script> tag in the <head> or the <body> tag, then you're not alone.

It mostly comes down to personal preference. However, because most of the times you'll want your JavaScript code to run after the web page and all its resources, e.g., stylesheets, graphics, videos, etc., have finished loading in the browser, I suggest you dump your JavaScript <script> tag at the bottom of your page.

Comments, comments, comments

One final thing to note about both code snippets above is the two forward slashes // before the text "JavaScript code goes here". This is how you comment a one-line JavaScript code.

When a comment spans over more than one line, you use /* Comment goes here */ to delimit a comment, just like you do in a stylesheet. Here's how it's done:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
	  </head>
	  <body>
        
      <script type="text/javascript">
	  /* JavaScript code
	  goes here */
      </script>
		
	  </body>
	  </html>
	  
	  

When the JavaScript interpreter in your browser comes across either '//' or '/* */', it just ignores whatever text is placed in between. Use comments in your code to remind your future self of what your code is designed to do. One day you'll be happy to have done so, just take my word for it!

Insert JavaScript in a separate file

If your script is longer than a few lines, or you need to apply the same code to several pages in your website, then packaging your JavaScript code into a separate file is your best bet.

In fact, just like having your CSS all in one place, well away from HTML code, having your JavaScript in its own file will give you the advantage of easily maintaining and reusing your scripts.

Here's how it's done:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
      <script type="text/javascript" src="yourjavascript.js"></script>
	  </head>
	  <body>
        
	  </body>
	  </html>
	
	  

As you can see, the <script> tag references an external file, "yourjavascript.js" that has the .js extension and contains the script that puts the magic into your web page.

Your first JavaScript-powered page: Hello World

Without further ado, let's see if JavaScript works in your browser.

Try out: embedded JavaScript in an HTML page

Between the <script> and </script> tags either in the <head> or the <body> of your HTML document, add the following line of code, just after the comment:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
	  </head>
	  <body>
        
	  <script type="text/javascript">
	  //JavaScript code goes here
	  alert('Hello World!');
      </script>
		
	  </body>
	  </html>
	
	  

This is your first JavaScript statement, that is, you've just instructed your web page to do something. Don't worry about the code just yet, we'll be coming back to the alert() command again and again in the following lessons.

Just notice the semicolon ( ; ) at the end of the statement. This is important: it tells the JavaScript interpreter that the statement is finished and whatever comes next is a different statement.

Now save your work and run the page in your favorite browser. You'll see an alert box popping up on page load. This is how the page looks in Firefox:

Illustration: JavaScript test with Hello World alert box

If your alert box is not popping up, then check that you've typed the JavaScript command exactly as it is in the sample code.

Make sure your <script>...</script> tags are there, that the text between the brackets is surrounded by quotes (' '), and that there is a semicolon ( ; ) at the end of the statement. Then try again.

Try out: JavaScript in a separate file

Create a new document in your text editor and save it as "helloworld.js". Important: the file extension has to be .js (this is the appropriate JavaScript file extension).

In the new document, paste in the JavaScript command from the previous example (no need to type the <script> ... </script> tags here):

	
	  alert('Hello World!');
	
	  

Now, go back to the HTML page, delete the previous JavaScript code, and add the <script> ... </script> tags in the <head> section of the page with a reference to the helloworld.js JavaScript file, like so:

	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>My first JavaScript page</title>
	  <script type="text/javascript" src="helloworld.js"></script>
	  </head>
	  <body>
        
	  </body>
	  </html>
	
	  

Save all your documents and run the HTML page in the browser. You should view the same alert box popping up as in the previous example.

If the code doesn't work, in your HTML document check that the filepath to the JavaScript file is correct, the filename spelling is accurate, and double-check that you've added a closing </script> tag. In helloworld.js make sure your JavaScript command is typed exactly the same as in the sample code above, then try again.

Summary

You've actually learned a lot in this lesson. You know how and where to include JavaScript in your web page, how to comment your JavaScript code and why this is a good idea, and finally you've just seen your web page come alive with your first JavaScript script.

Admittedly, an alert box saying "Hello World!" looks a bit dumb, but even alerts can be useful to quickly and easily test that JavaScript is enabled in your browser and your code is working.

It's time for a well deserved break. In lesson 3 you'll be tackling another core topic in your JavaScript journey: events. Get ready!


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 1: What is JavaScript

Lesson 3: Events >>