JavaScript Tutorial

Some Interesting Things About JavaScript

In JavaScript, functions are objects. They can be passed as arguments and be used as return values.

JavaScript is a prototype-based language. Object-oriented programming languages fall into one of two categories. There are class-based languages, like Visual Basic.NET, C# and Java, and prototype-based languages, like JavaScript. Prototype-based languages don't instantiate a new object on the basis of a class definition. They construct a new object by cloning the object's prototype.

JavaScript in HTML

The <script> Element

There are two ways to use the <script> element. One, embed JavaScript code directly into the document or, two, include JavaScript from an external file. To include inline JavaScript code, place JavaScript code inside the <script> element directly:

<script type="text/javascript">
	function hello() {
		alert("Hello, World!");
	}
</script>

The JavaScript code contained inside a <script> element is interpreted from top to bottom. The rest of the document content is not loaded and/or displayed until after all of the code inside the <script> element has been evaluated.

Before the modern browsers of today, it was neccessary to enclose the JavaScript in comment tags to prevent browsers that do not support the <script> tag from displaying the JavaScript code in the document. Though it may still work, this is no longer needed. The following is an example of this:

<script type="text/javascript"><!--
	function hello() {
		alert("Hello, World!");
	}
// --></script>

When utilizing inline JavaScript code, one can not have the string "</script>" anywhere in your code. The following code causes an error when loaded:

<script type="text/javascript">
	function sayScript(){
		alert("</script>");
	}
</script>

The browser sees the string "</script>" as if it were the closing </script> tag, but this problem can be easily avoided by escaping the "/" character:

<script type="text/javascript">
	function sayScript(){
		alert("<\/script>");
	}
</script>

The src attribute is required to include JavaScript from an external file. The value of src is a URI linked to a file containing JavaScript code:

<script type="text/javascript" src="example.js"></script>

An external file named example.js is loaded into the document in this example. The file itself need only contain the JavaScript code that would occur between the opening <script> and closing </script> tags. Processing of the document is halted until the external file is interpreted. There is also time taken to download it. One can omit the closing tag in XHTML documents:

<script type="text/javascript" src="example.js" />

Because it is invalid HTML and won't be handled properly by some browsers, this syntax should not be used in HTML documents.

Much like an <img> element, the <script> element's src attribute may be set to a full URI that exists outside the domain on which the HTML document exists.

<< < [Page 1 of 22] > >>