Watch our 3-minute video to find out how you can learn JavaScript with a live instructor.
Additional Resources

Quick JavaScript Recap

In this lesson of the JavaScript tutorial, you will learn...
  1. The basics of JavaScript in a context of a refresher.
  2. The fundamental data types of JavaScript
  3. That the DOM is not JavaScript
  4. What is the main object behind AJAX

This is just a refresher

The intent of this lesson is not to replace more comprehensive JavaScript classes or books. As a matter of fact, this lesson assumes you know your way around JavaScript but you may have forgotten one detail or two about the basics of the language.

Here we will go quickly over the fundamental building blocks of JavaScript and try to clarify some concepts that sometimes can be a little blurry.

Primitive data types

JavaScript comes with a number of data types that we can use in our variables. Let's look at them.

Null

Null is a data type that has only one possible value, null, which is also a reserved word in the language. We use null to represent a value that we don't know or that is missing.

var name = "Homer";
var ssn = null;

In the above example we know what to put in the name variable but we don't know yet what to put in the ssn variable. Maybe we will know what to put in there later in our program, but maybe not.

Undefined

The Undefined type also has a single value, undefined, and it is similar to null but not exactly the same thing.

JavaScript uses undefined as the default value for any variable that has not been initialized yet. Let's modify our previous example.

var name = "Homer";
var ssn;

Now the value of ssn is undefined because it is no longer initialized to null or anything else.

The undefined type is used a lot when we want to detect if a global variable has been already declared. Which is kind of a code smell anyway, as we will see in an upcoming lesson.

//Check if we already have a start time
if (START_TIME === undefined) {
 START_TIME = new Date();
}

Boolean

Boolean is a very common data type in every language. It has only two values, true and false, which are reserved words and, I hope, self-explanatory.

var enabled = true;
var disabled = false;

Number

The Number data type can represent two types of numeric values, 32-bit integers or 64-bit floating point numbers.

Number values are created using number literals, which can be in a few different formats.

var age = 25; // simple, decimal, integer
var price = 45.95; // floating point
var permissions = 0775; // integer in octal, 509 in decimal 
                        // (note the leading zero)
var flags = 0x1c; // integer in hexadecimal, 28 in decimal 
                  // (note the 0x prefix)
var measurement = 5.397e-9; // floating point in 
                            // scientific notation
   

String

String is a very popular data type and they are used to represent text. We spend a lot of time manipulating strings in pretty much any programming language.

We create strings using literal values enclosed in single or double quotation marks. These literal also support a few special encodings for common characters like new line, tab, and the quotation marks themselves. This is similar to what happens with strings in many other programming languages.

var name = 'Homer', lastName = "Simpson";
var host = 'Conan O\'Brien';
var path = 'c:\\temp\\dir\\myfile.txt';
var tabDelimited = "COL1\tCOL2\tCOL3\nVAL1\tVAL2\tVAL3";

Every value in JavaScript can be converted to a string by using the toString() method, like var s = myValue.toString();.

Native Types

In addition to the primitive data types we just saw, JavaScript also provides a few other data types, which are implemented as objects.

Date

We can store date values using Date objects. The Date object stores the date and time information internally as the number of milliseconds since January 1st 1970.

There aren't date literals in the language, so we have to explicitly create a Date object when we need one.

var rightNow = new Date(); // current date and time
var holiday = new Date(2008, 6, 4); // 4th of July, note the  
                  // 0-based month number
var birth = Date.parse('7/4/2008'); // 4th of July, format varies with browser 
                                    // locale (avoid this)

There two important pitfalls in the above example: the month is a number from 0 to 11 when passed as a parameter and the parse-able string formats vary by browser implementation and by user locale, so we'd better off just avoid parsing altogether.

Array

How useful would be our programs if we couldn't organize the data in arrays or other collection structures? I guess not very much.

Arrays are very powerful in JavaScript and they kind of blur the lines between arrays and custom objects.

The Array object can be instantiated with both a constructor call or using literals. The array indices are not necessarily contiguous or numeric or even of the same data type.

var CITIES = new Array();
CITIES[0] = 'Albuquerque';
CITIES[9] = 'Tampa';
var TEAMS = [ 'Cubs', 'Yankees', 'Mariners' ];
var BANDS = [ ];
BANDS['rock'] = "Beatles, Rolling Stones, Pink Floyd";
BANDS['punk'] = "Sex Pistols, Ramones, Dead Kennedys";
BANDS[1992] = "Nirvana, Pearl Jam, Soundgarden, Metallica";

Object

The Object type serves as the base for all the objects in JavaScript, regardless of their data type or how they were created.

The Object type is also used when we want to create custom objects. We can create new objects using a constructor call or a literal. We will cover this is greater detail in a future lesson.

var employee = new Object();
employee.name = 'Homer Simpson';
employee.badgeNumber = 35739;
var boss = { }; //literal syntax, empty though
boss.name = 'Montgomery Burns';
boss.badgeNumber = 1;
employee.reportsTo = boss;

Regular Expressions

Regular Expressions is a syntax used to find occurrences of a string pattern inside a larger string. It has historically been more popular in Unix environments and in Perl programs, but it has gained some adoption in many other programming languages as well.

Regular expressions is one of these technologies with a measurable learning curve but that can have a big payoff depending on the type of work you do.

JavaScript implements regular expressions with RegExp objects. It also support the Perl-syle literals.

var text = "Webucator";
var pattern = new RegExp('cat', 'g');
var samePattern = /cat/g; //using the literal syntax
alert( pattern.test( text ) );// shows 'true'

Functions

Functions in JavaScript are more than just static blocks of code. They are Function objects that we use just like any other data type value, e.g. we can pass functions to other functions, we can store a function in a variable, we can modify a function, etc.

We will have a lot to talk about functions in one of our lessons. For now let's just remember how we declare and call functions.

//declare the function
function sayHowMuch(name, price, quantity) {
 var finalPrice = price * quantity;
 alert('The price for ' + quantity + ' ' + 
   name + '(s) is $' + finalPrice);
}

//call the function with arguments
sayHowMuch('ice cream cone', 1.99, 3);
sayHowMuch('Movie ticket', 10.00, 5);

The DOM is not JavaScript

A common source of confusion is the relationship between the browser DOM (Document Object Model) and the JavaScript global objects.

JavaScript being an interpreted language with a runtime execution engine, it needs a host environment to instantiate the engine and forward the JavaScript code to it. The browser is one of many hosts for JavaScript. Other hosts are Adobe Flash plugins (via ActionScript), desktop widgets (like Yahoo! Widgets, MS Gadgets, OS X Dashboard Widgets), Firefox browser add-ons, and even some kinds of electronic equipment.

All that said, the browser was the originally intended host for JavaScript and by far the most common one.

The DOM

It's important to understand that the DOM is a standard that has nothing to do with JavaScript. It was created by the W3C to normalize the browser vendors' implementations of Dynamic HTML.

The DOM is an API that enables programatic access to the HTML document structure, for reading or modification purposes. When we write code like document.getElementById('abc') we are using the DOM.

With the DOM we can traverse our entire HTML document looking for specific HTML elements, which are called nodes, or even create new elements and append them pretty much anywhere we want inside the HTML document.

The window object

In browser scripts, the document object is actually a property of the window object, which is the default (or global) object of JavaScript in that environment. So typing window.document.body is the same as typing document.body. The DOM starts at the document object.

There are other things one may think are part of JavaScript when, in fact, they're browser-specific features, like the alert(), prompt(), setTimeout(), and open() functions. These are just methods of the window object, not part of JavaScript per se.

The XMLHttpRequest object

Another important object that we use a lot in JavaScript these days is the XMLHttpRequest object. This is the object that powers the AJAX functionality in a lot of web pages.

This object is also not part of JavaScript. It can be used from JavaScript but it isn't part of the language.

We won't cover AJAX here but it suffices to understand that this object allows our scripts to initiate a request to an URL and collect the server response without the need to reload the entire page.

function saveUser(name, age) {
 //the following line is actually a grossly simplified version
 // that is not supported in all browsers
 var ajax = new XMLHttpRequest(); 

 ajax.open('POST', '/users/update', true);
 ajax.onreadystatechange = function () {
  if (ajax.readyState == 4) {
   alert('User ' + name + ' updated.');
  }
 }; 

 ajax.send( 'userName=' + name + '?userAge=' + age  );
}
saveUser('Joe Doe', 54);

Quick JavaScript Recap Conclusion

We hope that after this short tour of JavaScript data types and the browser execution environment you will be able to absorb all the new concepts you are about to see in the remainder of the course.

Because of the syntax similarities with C-style languages, it's often possible that we mix-up what is available in JavaScript so this lesson can serve as a quick reminder or cheat-sheet when needed.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of http://www.learn-javascript-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm