Getting Started

Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of browsers.

JavaScript language provides user interactivity with a web page after the page loads, developers commonly use it for some of the following functions:

  • Dynamically add, edit, and remove HTML elements and their values

  • Validate web forms before submission

  • Create cookies to store and retrieve data on a user's computer for future visits

Before getting started, there are just a few language basics to be aware of:

  • To include JavaScript code in an HTML file, you must place the code inside script tags and include the text/javascript type attribute (Listing 1).

  • All JavaScript statements end with a semicolon.

  • The language is case sensitive.

  • All variable names must begin with a letter or underscore.

  • You can use comments to identify certain lines of your script. You write comments using a double forward slash (//) followed by the comment.

  • You can also use comments to comment out script. A good way to comment out multiple lines of script is by using /* your script goes here */. Any script within the stars /**/ doesn't run during execution.

Listing 1. The script tags and type attribute are required to include JavaScript code in an HTML file

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

To hide JavaScript code from browsers that do not support it or if a user has it turned off, simply use the comment tag before and after the JavaScript statement (Listing 2).

Listing 2. Use comments to hide JavaScript code from browsers that do not support it

<script type="text/script">

<!-- Example Statement Here -->

</script>

The most commonly used way to include JavaScript code in a web page is to load it from an external JavaScript file using the src attribute in the script tag (Listing 3).

Listing 3. Including an external JavaScript file in an HTML file

<script type="text/script">

<!-- Example Statement Here -->

</script>

External JavaScript files are the most common way to include JavaScript code for a number of practical reasons:

  • Search engines can crawl and index your web site faster if there is less code within your HTML page.

  • Keeping your JavaScript code separate from your HTML is cleaner and ultimately easier to manage.

  • Because you can include multiple JavaScript files in your HTML code, you can separate the JavaScript files into different folder structures on your web server, similar to images, which is an easier way to manage your code. Clean, organized code is always key to easily managing your website.

<html>

<script type="text/script">

<!-- Example Statement Here -->

</script>

<body>

</body>

</html>