News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

JavaScript Tutorial – 02 – Using JavaScript

JavaScript tutorials

To embed a JavaScript into a web page the HTML <script> element is used with the type attribute set to “text/javascript”.

<script type="text/javascript"> </script>

Printing output

The first script to learn is the document.write method for dynamically outputting HTML onto the page.

<script type="text/javascript">
  document.write("Hello World!");
</script>

Statements in JavaScript end with a semicolon, but a newline also functions as the end of a statement. Therefore, semicolons are not required unless there are several statements on the same line.

<script type="text/javascript">
  document.write("Hello World"); document.write("!")
</script>

Comments and whitespace

JavaScript uses the standard C++ comment notation, with both single-line and multi-line comments. As in HTML, whitespace is ignored in JavaScript, so extra spaces can be used to make the scripts more readable.

<script type="text/javascript"> 
 // single-line comment
 /* multi-line
    comment */
</script>

Hello World

The HTML document below contains a Hello World JavaScript.

<html>
<head><title>Learning JavaScript</title></head>
<body>
  <script type="text/javascript">document.write("Hello World");</script>
</body>
<html>

When this document is viewed in a browser the script is executed as soon as the page loads and the text is displayed. Note that the script runs on the client-side. Therefore, there is less load on the server compared to server-side scripts. However, this also means that it’s up to the client whether the script is executed or not. The client may have disabled JavaScript or use an old browser that doesn’t support it.

Compatibility

If the browser doesn’t support JavaScript the script will be displayed as normal HTML. To prevent this it can be surrounded with the HTML comment tag, which effectively hides the script.

<script type="text/javascript"> <!--
//--> </script>

There’s also the <noscript> HTML element. This element presents an alternative message that can only be seen by browsers that don’t support scripts. However, since JavaScript is the most popular scripting language it works with all major browsers today.

<noscript>
 Your browser doesn't support JavaScript.
</noscript>

External script file

Another way to include JavaScript is by saving the script in a file with a .js file extension. This external script can then be embedded in a page by pointing to the file with the src attribute of the script tag. This way several pages can use the same scripts without having to duplicate them on every page.

<script type="text/javascript" src="MyJS.js"></script>
Recommended additional reading:
Sams - Teach Yourself JavaScript in 24 Hours