facebook google plus twitter
Webucator's Free JavaScript Tutorial

Lesson: JavaScript Basics

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

In this lesson, you will learn how to get started with the basics of JavaScript.

Lesson Goals

  • Learn to work with the HTML DOM.
  • Learn to follow JavaScript syntax rules.
  • Learn to write JavaScript inline.
  • Learn to write JavaScript in script blocks.
  • Learn to create and link to external JavaScript files.
  • Learn to work with JavaScript objects, methods, and properties.
  • Learn to reference HTML elements with JavaScript.

The Name "JavaScript"

In this manual, we refer to the language we are learning as JavaScript, which is what it is usually called. However, JavaScript was invented by Netscape Communications and is now owned by Oracle Corporation. Microsoft calls its version of the language JScript. JavaScript and JScript are both implementations of EcmaScript, but everyone still refers to the language as JavaScript.

What is ECMAScript?

ECMAScript, sometimes abbreviated as "ES", is a scripting language specification maintained and trademarked by Ecma International, a Europe-based industry association dedicated to technology and communications standards. The specification for the most-recent standard version of ECMAScript - "ES6" or, as it is officially know, "ECMA-262 6th Edition, The ECMAScript 2015 Language Specification," can be found at:

http://www.ecma-international.org/ecma-262/6.0/

As we mentioned above, JavaScript - the scripting language you are learning here and whose code is run by the browsers you (or others) use to visit the pages you build - is an implementation of ECMAScript.

Keep in mind that ECMAScript evolves over time: new features are added, new syntax is adopted, etc. Like CSS, HTML, and other client-side technologies, JavaScript is an implementation of a standard (ECMAScript) by browsers - please be aware that all browsers won't implement (or implement in the same manner) all newer features of ECMAScript, and that later versions of browsers will implement newer features over time.

The HTML DOM

The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. Below is a simplified version of the HTML DOM.HTML DOM

As shown, the top-level object is window. The document object is a child of window and all the objects (i.e., elements) that appear on the page (e.g., forms, links, images, tables, etc.) are descendants of the document object. These objects can have children of their own. For example, form objects generally have several child objects, including text boxes, radio buttons, and select menus.

JavaScript Syntax

Basic Rules

  1. JavaScript statements end with semi-colons.
  2. JavaScript is case sensitive.
  3. JavaScript has two forms of comments:
    • Single-line comments begin with a double slash (//).
    • Multi-line comments begin with "/*" and end with "*/".

Syntax

// This is a single-line comment.

/*
	This is
	a multi-line
	comment.
*/

Accessing Elements

Dot Notation

In JavaScript, elements (and other objects) can be referenced using dot notation, starting with the highest-level object (i.e., window). Objects can be referred to by name or id or by their position on the page. For example, if there is a form on the page named "loginform", using dot notation you could refer to the form as follows:

Syntax

window.document.loginform

Assuming that loginform is the first form on the page, you could also refer to it in this way:

Syntax

window.document.forms[0]

A document can have multiple form elements as children. The number in the square brackets ([]) indicates the specific form in question. In programming speak, every document object contains a collection of forms. The length of the collection could be zero (meaning there are no forms on the page) or greater. In JavaScript, collections (and arrays) are zero-based, meaning that the first form on the page is referenced with the number zero (0) as shown in the syntax example above.

Square Bracket Notation

Objects can also be referenced using square bracket notation as shown below:

Syntax

window['document']['loginform']

// and

window['document']['forms'][0]

Dot notation and square bracket notation are completely interchangeable. Dot notation is much more common; however, as we will see later in the course, there are times when it is more convenient to use square bracket notation.

Where Is JavaScript Code Written?

JavaScript code can be written inline (e.g., within HTML tags called event handlers), in script blocks, and in external JavaScript files. The page below shows examples of all three.

Code Sample:

JavaScriptBasics/Demos/javascript-1.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Page</title>
<link href="style.css" rel="stylesheet">
<script>
	window.alert("The page is loading");
</script>
</head>
<body>
<p>
	<span onclick="document.body.style.backgroundColor = 'red';">Red</span> |
	<span onclick="document.body.style.backgroundColor = 'white';">White</span>
</p>
<script src="script-1.js"></script>
</body>
</html>

Code Explanation

Code Sample:

JavaScriptBasics/Demos/script-1.js
document.write("<p>Hello, there!</p>");

Code Explanation

As this page loads, an alert will pop up that says "The page is loading" as shown below: Popup Alert

After the user clicks the OK button, the page will finish loading and will appear as follows:Loaded Page

The text "Hello, there!" is written dynamically by the code in JavaScriptBasics/Demos/script-1.js. We will look at the code in this file and in JavaScriptBasics/Demos/javascript-1.html again shortly.

In HTML 4, the <script> tag must contain a type attribute set to text/javascript like this: <script type="text/javascript">.

In HTML5, the assumed (default) value for type is text/javascript so it's not necessary to include the attribute, but it doesn't hurt.

The "javascript" Pseudo-Protocol

Try this:

  1. Open your browser.
  2. In the location bar, type in javascript:alert("Hello world!"); like so: Location Bar
  3. Press Enter.

You should get an alert reading "Hello world!". The javascript: prefix is called a pseudo-protocol, because it mimics the protocol syntax (e.g., like http:, 0.:, and mailto:). It provides an easy way to test JavaScript on a page. It can also be used in links as in the demo below:

Code Sample:

JavaScriptBasics/Demos/psuedo-protocol.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Pseudo-Protocol</title>
</head>
<body>
<p><a href="javascript:alert('Hello world!');">Say hello</a></p>
</body>
</html>

Code Explanation

When the user clicks the link, the JavaScript alert will execute.

This is generally considered a bad practice. The preferred way to handle this is to use the href attribute to provide an alternative page in case JavaScript is not enabled. You could provide a generic page with a "JavaScript is required" message or, even better, you could provide a page that accomplishes the same task as the alert as in the following the demo:

Code Sample:

JavaScriptBasics/Demos/better-than-psuedo-protocol.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Better than Pseudo-Protocol</title>
</head>
<body>
<p><a href="hello-world.html" onclick="alert('Hello world!'); return false;">Say hello</a></p>
</body>
</html>

Code Explanation

When the user clicks the link...

  • If JavaScript is enabled, the alert pops up and the return false; statement explicitly cancels the link's default behavior.
  • If JavaScript is NOT enabled, the link takes the user to hello-world.html.

JavaScript Objects, Methods, and Properties

JavaScript is used to manipulate or get information about objects in the HTML DOM. Objects in an HTML page have methods (actions, such as opening a new window or submitting a form) and properties (attributes or qualities, such as color and size).

To illustrate objects, methods and properties, we will look at the code in JavaScriptBasics/Demos/javascript-2.html, a slightly modified version of JavaScriptBasics/Demos/javascript-1.html, which we looked at earlier, and at the code in JavaScriptBasics/Demos/script-2.js.

Code Sample:

JavaScriptBasics/Demos/javascript-2.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Page</title>
<link href="style.css" rel="stylesheet">
<script>
	//Pop up an alert
	window.alert("The page is loading");
</script>
</head>
<body>
<p>
	<span onclick="document.body.style.backgroundColor = 'red';">Red</span> |
	<span onclick="document.body.style.backgroundColor = 'white';">White</span> |
	<span onclick="document.body.style.backgroundColor = 'green';">Green</span> |
	<span onclick="document.body.style.backgroundColor = 'blue';">Blue</span>
</p>
<script src="script-2.js"></script>
</body>
</html>

Code Explanation

Code Sample:

JavaScriptBasics/Demos/script-2.js
/*
This script simply outputs
	"Hello, there!"
to the browser.
*/
document.write("<p>Hello, there!</p>");
            

Code Explanation

Methods

Methods are the verbs of JavaScript. They cause things to happen.

window.alert()

HTML pages are read and processed from top to bottom. The JavaScript code in the initial script block at the top of JavaScriptBasics/Demos/javascript-2.html calls the alert() method of the window object. When the browser reads that line of code, it will pop up an alert box and will not continue processing the page until the user presses the OK button. Once the user presses the button, the alert box disappears and the rest of the page loads.

document.write()

The write() method of the document object is used to write out code to the page as it loads. In JavaScriptBasics/Demos/script-2.js, it simply writes out "Hello, there!"; however, it is more often used to write out dynamic data, such as the date and time on the user's machine.

Arguments

Methods can take zero or more arguments separated by commas.

Syntax

object.method(argument1, argument2);

The alert() and write() methods shown in the example above each take only one argument: the message to show or the HTML to write out to the browser.

Properties

Properties are the adjectives of JavaScript. They describe qualities of objects and, in some cases are writable (can be changed dynamically).

document.body.style.backgroundColor

The style property of the document object is read-write. Looking back at JavaScriptBasics/Demos/javascript-2.html, the four span elements use the onclick event handler to catch click events. When the user clicks on a span, JavaScript is used to set the style of the body to a new color, in the same way that we might use CSS to style the page with background-color:red or background-color:white.

The Implicit window Object

The window object is always the implicit top-level object and therefore does not have to be included in references to objects. For example, window.document.write() can be shortened to document.write(). Likewise, window.alert() can be shortened to just alert().

Alerts, Writing, and Changing Background Color

Duration: 5 to 15 minutes.

In this exercise, you will practice using JavaScript to popup an alert, write text to the screen, and set the background color of the page.

  1. Open JavaScriptBasics/Exercises/alert-write-bgcolor.html for editing.
  2. In the head of the file, add a JavaScript alert which pops up the message "Welcome to my page!" when the page loads.
  3. Add click handlers to the two buttons to allow the user to change the background color of the page to red or to blue.
  4. In the script at the bottom of the page, use JavaScript to write the text "This text was generated by JavaScript" to the page.
  5. Test your solution in a browser.

Solution:

JavaScriptBasics/Solutions/alert-write-bgcolor.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Alert, Write, BGColor</title>
<script>
	window.alert("Welcome to my page!");
</script>
</head>
<body>
<form>
	<p>Click the button to turn the page:<p>
	<button onclick="document.body.style.backgroundColor = 'red'; return false">Red</button>
	<p>Click the button to turn the page:<p>
	<button onclick="document.body.style.backgroundColor='blue'; return false">Blue</button>
</form>
<hr>
<script>
	document.write('This text was generated by JavaScript');
</script>
</body>
</html>

Code Explanation

We use alert() to generate the popup the head and document.write() to write to the screen at the bottom of the page. We use onclick="document.body.style.backgroundColor='red' to add a click handler to the button; return false ensures that the page does not reload when the button is clicked.