Type Here to Get Search Results !

Lesson 2: Your First JavaScript

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:



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:



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



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:



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:



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:



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:



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!

Post a Comment

19 Comments
  1. I think that everything published made a ton of sense.
    But, think about this, suppose you added a little information? I am not
    saying your content is not solid., but suppose you added a headline that grabbed a person's attention? I
    mean "Lesson 2: Your First JavaScript" is a little plain. You
    ought to look at Yahoo's home page and see how they write post titles to get
    viewers to open the links. You might add a video or a related picture
    or two to grab people interested about what you've written. Just my opinion, it might bring your posts a little bit more interesting.

    ReplyDelete
  2. Hi, always i used to check weblog posts here in the early
    hours in the break of day, because i enjoy to gain knowledge of more and more.

    ReplyDelete
  3. Thank you for another magnificent article. The
    place else could anybody get that kind of info in such an ideal way of writing?
    I've a presentation next week, and I am on the look for
    such information.

    ReplyDelete
  4. If you wish for to get a great deal from
    this article then you have to apply these strategies to your won web site.

    ReplyDelete
  5. I think this is one of the most vital info for me. And
    i'm glad reading your article. But wanna remark on few general things, The site style
    is great, the articles is really great : D. Good job, cheers

    ReplyDelete
  6. When I initially left a comment I appear to have clicked on the -Notify me when new
    comments are added- checkbox and now every time a comment is
    added I recieve four emails with the exact same comment.
    Is there a way you can remove me from that service? Kudos!

    ReplyDelete
  7. I think this is among the most significant info
    for me. And i am glad reading your article. But wanna remark on some general things,
    The site style is perfect, the articles is really nice : D.
    Good job, cheers

    ReplyDelete
  8. If some one wants expert view about blogging after
    that i suggest him/her to visit this webpage, Keep up the
    pleasant job.

    ReplyDelete
  9. Hi my friend! I want to say that this post is awesome,
    great written and come with almost all important infos.
    I'd like to look more posts like this .

    ReplyDelete
  10. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much.

    I hope to give something back and help others like you helped me.

    ReplyDelete
  11. Hi there, just wanted to tell you, I loved this article.
    It was funny. Keep on posting!

    ReplyDelete
  12. I visited various websites but the audio feature for audio songs current at this website is
    in fact superb.

    ReplyDelete
  13. I'd like to find out more? I'd care to find out
    more details.

    ReplyDelete
  14. When some one searches for his vital thing, thus he/she wants to be available that in detail, thus that thing is
    maintained over here.

    ReplyDelete
  15. Wonderful, what a weblog it is! This weblog gives valuable information to us, keep it up.

    ReplyDelete
  16. It is the best time to make some plans for the future and it is
    time to be happy. I've read this post and if I could I want to suggest you few interesting things or advice.
    Maybe you could write next articles referring to this article.
    I wish to read even more things about it!

    ReplyDelete
  17. Wow, awesome weblog structure! How long have you been running a blog for?
    you make blogging glance easy. The total look of your website is great, as well
    as the content material!

    ReplyDelete
  18. Woah! I'm really digging the template/theme of this blog.

    It's simple, yet effective. A lot of times it's very hard to get that "perfect balance"
    between user friendliness and appearance. I must say you
    have done a great job with this. Additionally, the blog loads very quick
    for me on Opera. Excellent Blog!

    ReplyDelete
* Please Don't Spam Here. All the Comments are Reviewed by Admin.