JavaScript Primer: Understanding the Script Element

JavaScript code is added to an HTML document using the script element. There are two ways to use the script element, and you can see both of them in Listing 5-1. The first way is to apply the src attribute and import a separate file that contains JavaScript statements. This is what I did with the AngularJS library file, like this:

<script src=”angular.js”></script>

You can also create inline scripts by putting JavaScript statements between the script element tags, like this:

<script type=”text/javascript”>



For real projects, you will usually use external files because they are easier to manage, but for the examples I create in this book it is often more convenient for me to be able to demonstrate the HTML and the JavaScript in the same file.

The inline script in this example contains a statement that calls the console.log method, which writes a message to the JavaScript console. The console is a basic (but useful) tool that the browser provides that lets you display debugging information as your script is executed. Each browser has a different way of showing the console. For Google Chrome, you select JavaScript console from the Tools menu. You can see how the console is displayed in Chrome in Figure 5-2.

Tip Notice that the Chrome window shown in the figure has an AngularJS tab. This is added by the Batarang extension that I described in Chapter 1 and is useful for debugging AngularJS apps.

You can see that the output from calling the console.log method is displayed in the console window, along with the details of where the message originated (in this case on line 7 of the jsdemo.html file). In this chapter, I won’t show screenshots; I’ll show just the results from the examples. So, for example, for Listing 5-1, the output is as follows:


I have formatted some of the results later in the chapter to make them easier to read. In the sections that follow, I’ll show you the core features of the JavaScript language. If you have had any experience programming in any other modern language, you will find the JavaScript syntax and style familiar.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *