Learn JavaScript

Welcome to JavaScript XML, home to all of the JavaScript, programming, XML, and JSON examples and source code you need. Just quality content - and 100% free!

All source code on this website is released under the MIT License.

Topics:

To learn about my other projects, please visit my blog at http://fonte.me

Privacy Policy

JavaScript Basics

JavaScript is a unique and beautiful language, both expressive and intuitive. In this introductory section I'll outline the basic features of the JavaScript language, along with a brief initial look at programming in JavaScript.

JavaScript inherits from both functional languages and object-oriented languages. The main attribute JavaScript retains from it's functional language heritage is the idea of a first-class function: a function is treated as a "first-rate citizen" in the programming heirarchy. This means you can pass a function as an argument to another function, and it is treated as just a regular variable passed in to the called function.


JavaScript Example 1: First-class Functions

                    	
//function definition - function passed in to this one
function loopFunc(loopCount, param1) {
	//loop a number of times equal to loopCount
	for(var i = 0; i < loopCount; i++) {
		//each time the loop is run, call this function
    	param1();
    }
}

//prints 'Hello, World!' to the debug console (Firebug, IE Dev Tools, Chrome Developer Tools, etc.)
function printToConsole() {
	console.log('Hello, World!');
}

loopFunc(10, printToConsole );

                        
                    

This code will pass in the function that prints to the console, and the other function will then loop through it ten times, effectively printing "Hello, World!" to the console ten times.

JavaScript also is devoid of static-typing, that is, type checking at compile-time. Variables do not require a type to be declared when they are instantiated. The system JavaScript uses is known as dynamic typing - variable types are discerned at run-time, in this case, based on the values of the variable, and the way in which it is used.

Declaring variables in JavaScript is fairly straightforward. Generally, you'll start out by typing the "var" keyword, followed by the name of the variable(s), and ending with an initialization statement, if any is desired. Using the "var" keyword declares a variable in the local scope, which means it "lives" in the function or block you declared it in. Declaring variables without the "var" keyword generally makes the variable a global variable, which means all functions can access and change it.


JavaScript Example: Declaring and Initializing Variables

                    	
//using var declares the variable in the local scope
var x = 0;

if(x == 0) {
	//this variable "y" only exists inside of the if statement - it has local scope in the if statement.
	var y = 10;
	//this variable "z" has global scope
	z = 'a global variable';
}
                        
                    

Local variables declared with the "var" keyword have scope within the block they are declared in. A block is generally denoted by a set of curly braces, { }. Everything in between the curly braces is at the same level of scope, unless there are nested curly braces, like so:

                    	
for(var x = 0; x < 100; x++) {
	var outerVariable = 100;
    if(x > 20) {
    	var innerVariable = 200;
    }
}                        
                        
                    

In this example, the "outerVariable" has scope in the "for" statement and in the "if" statement, whereas the "innerVariable" only has scope in the "if" statement - once the if statement ends, "innerVariable" is out of scope and doesn't exist anymore.

This concludes the introduction to JavaScript basics. In the next section, we'll take a closer look at control statements for changing the flow of program execution ("if...else...else if" statements and "switch" statements).

Program Flow and Control Statements (If and Switch)

Being able to branch program flow based upon conditional expressions (that is, logic tests that evaluate to true or false) is an essential part of programming in any language. JavaScript offers a fairly standard array of program flow or control keywords: "if", "else if", "else", "switch...case" and the ternary operator (we'll skip the last one for now).

The first step towards using the if statement is to understand the syntax of logical expressions in JavaScript. The main Boolean operators are:

Operator Meaning
== Equals
!= Not Equal
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
=== Equals (Type Equality Check)
!== Not Equals (Type Equality Check)
&& And Operator
|| Or Operator

A few of these operators require some explanation. Most of the operators are fairly standard in math, but a few might not be. The "and" operator allows you to require two or more conditions to evaluate to true for the entire conditional expressions to evaluate to true. The "or" operator requires one or both of the expressions to evaluate to true for the entire expression to evaluate to true.

When you're evaluating multiple conditional expressions at once, it's usually a good idea to use parentheses to group your various component conditional expressions, especially if you're using the "and" or "or" operators to test multiple conditions. Here's an example of this kind of parenthesized expression:

                    	
var x = 5;
var y = 10;

if( (x < y) && (y < 50) ) {
	//do something here
}
                        
                    

The basic design of the "if" statement is to evaluate a logic test, and if it ultimately evaluates to true, the block of code inside the if statement is executed; otherwise, it is skipped.


The If Statement


                    	
var x = true;
var y = false;

if(x || y) {
	console.log('x is true or y is true');
}
                        
                    

Using "if" by itself is useful, but it isn't the whole selection of code branching statements. The other two primary branching keywords are "else if" and "else". If a preceding "if" statement evaluates to false, the next "else if" or "else" statement will be evaluated. Oftentimes, there will be a progression of "if", "else if", and "else" statements in a given conditional section of code. It's worth noting that there can only be one "else" statement per group of branching statements, though there can be a theoretically unlimited number of "else if" statements.


If, Else If, Else Statements


                    	
var x = 10;
var y = 20;
var z = 100;

if(x > y) {
	//this block is skipped
}
else if(z > 50) {
	//this block runs
}
else {
	//this block is never reached
}                   
                        
                    

The other key part of manipulating program flow is the "switch" statement. If you find yourself using a lot of "else if" statements, you might be better off using the "switch" statement. A switch statement takes a variable as an argument, and then the value of the variable is compared against each of the "case" statements.


Switch Statement Example


                    	
var toSwitch = 'hello';

switch(toSwitch) {
    case 'abc':
    	console.log('alphabet');
    	break;
    case '123':
    	console.log('numbers');
		break;
    case 'epic':
    	console.log('epic code');
        break;
    case 'hello':
    	console.log('hello world');
    	break;
    default:
    	console.log('unknown input');
}                        
                        
                    

Besides the switch and case statements seen here, there are two other important keywords to take note of. First of all, there is the "break" keyword; this ends the execution of the switch statement. Without it, the switch statement would continue through all following cases after the matched one. The other important [optional] keyword is the "default" keyword: this term is where program execution flows to if none of the case statements match.

Loops in JavaScript

The looping functionality JavaScript offers is very similar to other C-style languages. If you’re not familiar with C-style languages, or if you’re looking for a refresher on these concepts, this tutorial will get you up to speed quickly.

The simplest loop is the “while” loop. It takes an argument of a Boolean conditional expression, and if the expression evaluates to true, the loop is run. Once the code runs again, the Boolean test is checked again, and if it’s true, the loop runs again. This process continues until the Boolean test evaluates to false.

Here’s an example of a while loop:


A Simple While Loop


                	
var x = 0;
while(x < 10) {
	console.log(x);
	x++;
}
					
                

This loop will output digits from 0 to 9, then exit.

A common variant of the while loop is the do...while loop. The main diifference of the do...while loop, compared to the while loop, is that the code block always runs at least once - then the logic test is performed at the bottom of the loop. If it’s true, the loop runs again - otherwise, it exits. Here’s an example of a do...while loop:


A Do...While Loop


                	
var x = 0;
var y = 10;

do {
	x += 1;
	y += 10;

} while( (x + y) < 50) ;
					
                

In actual practice, looping often serves the purpose of iterating over the items in a collection - in JavaScript, usually an array. You could do this using a while loop, but there’s a much better solution - the “for” loop. The for loop combines an initialization statement, a conditional logic test, and a final statement that is typically used to increment or decrement the counter variable.

What typically happens is the counter variable is initialized, then tested to see if it’s below or above a certain value. If the logic test evaluates, the loop body is run, then at the end of the loop. the increment or decrement statement is run - then the whole process starts again, without the intialization statement (the variable is only initialized once when the for loop is first run).

Here’s an example of a for loop:


For Loop through a Fibonnaci Series Array


                	
//array of the first 10 Fibonacci series numbers
var fibArray[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
//loop through the ten Fibonacci numbers
for(int i = 0; i < 10; i++) {
	console.log(fibArray[i]);
}
					
                

There are two important keywords/statements that are useful when you’re working with looping constructs. First there is the “break” keyword, which exits the current loop (whichever loop contains the scope in which the “break” keyword is used). Secondly, there is the “continue” keyword, which proceeds to the next iteration of the loop, ignoring code following the continue statement. These keywords are used inside of an if block, so the loop is only altered when and if a certain conditional expression evaluates to true.

Here’s an example of using break:


Using the "break" Keyword


                	
var x = 0;
while(true) {
	x++;
	//end the loop when x is more than 10
	if(x > 10) {
		break;
	}
}
					
					
                

JavaScript Arrays Tutorial

One of the most useful fundamental data structures in computer science and programming is the array. An array is a single or multi-dimensional collection of variables of a certain type. You can have a one-dimensional array of integers, or a two-dimensional array of strings. We’ll start by looking at one-dimensional arrays:

                	
//literal array syntax - initializing the array with an array literal.
var integerArray = [1, 2, 3, 4];
					
                

This array contains four items. The indexes range from 0 to 3; array indexes always start at zero in JavaScript (and most other languages). This means “integerArray[0]” = 1, “integerArray[3]” = 4, and “integerArray[4]” will cause an error.

Arrays have a number of built-in functions and properties, including push to add an item to the end of an array, pop to remove an item from the end of an array, length to determine the number of elements in the array, and more.

The array function “indexOf” is very useful when you need to find an element in an array. This function will search the array for the value it’s provided, and return the index in the array where that value is (if it is in fact in the array). If no match is found, it returns -1.

When you’re creating an array, you might not know what the initial values should be. In that case, simply declare the array as a new Array object, like so:

                	
var myArray = new Array();
					
                

You can then add elements to the array later, by using the following pattern of code:

                	
myArray[0] = “hello”;
myArray[1] = “world”;
					
                

Or, you can use push to move elements onto the array, one by one:

                	
myArray.push(‘Hello’);
myArray.push(‘World’);
					
				

Creating multi-dimensional arrays in JavaScript is somewhat arcane in comparison to other programming languages; you have to create nested arrays, rather than simply declaring the array as multi-dimensional. Here’s an example of a nested array, equivalent to two dimensions:

                	
myMultiDimArray = [ [5, 7], [1, 2], [8,4], [1, 2], [3, 1] ];
//logs the value 2
console.log(myMultiDimArray[1][1]);

//logs the value 1
console.log(myMultiDimArray[3][0]);
					
                

Nested arrays can be a confounding occurrence if you’re not that familiar with arrays in various languages. What’s basically happening here is that the first index/set of square brackets selects which of the inner arrays you’d like to examine, and the second index/set of square brackets determines which value of the inner array you want.

You can think of nested arrays somewhat like having a few TV series on DVD. In front of you are 5 different TV show seasons. You select the first one, and upon opening the TV series box, there are four DVDs to choose from. Once you’ve chosen a DVD, there are three episodes per DVD to choose from. This is roughly equivalent to a three-dimensional nested array.

JavaScript Functions

If there’s one great feature of JavaScript, it’s the support it has for functional programming. Above and beyond the taken for granted feature of supporting subroutines and functions, JavaScript has first-class functions and anonymous functions. We’ll get to these latter two special features in a bit, but lets start with plain-old functions first.

The purpose of functions is to break up work into manageable, reusable pieces. Suppose we want to write a function that calculates the square of an input value, and then returns the squared output. We could write something like the following:

                	
function square(x) {
    return x * x;
}

//logs 16 to the console
console.log(square(4));
					
				

The preceding was a fairly trivial example, but it conveys the main components of a function rather well - the “function” keyword signifies that a function is to be declared. Next is the name of the function - in this case, “square”. There is then a set of parentheses, which can either be empty if there are no function inputs/parameters, or they can contain a comma-separated list of the various function parameters. Note that in JavaScript, you do not list the data types of function parameters; JavaScript is not a statically typed language, where the compiler catches type errors; the variables must be listed without any data type for the code to work.

Function composition is possible in JavaScript, as with many languages. For example, you can nest functions inside one another, effectively passing the return value of the innermost function to the next innermost function as an argument, and proceeding onwards until the final, outermost function is executed, and that final return value is the end result of the composed functions’ execution. Here’s an example of such a process:

                	
function a(x) {
	return x * 2;
}

function b(x) {
	return x * 10;
}

//finalVal will have the value 40
var finalVal = b(a(2));
					
                

One particularly common occurrence, if you use libraries like jQuery or Dojo, is the use of a callback function - which is usually an anonymous function. Anonymous functions are just like regular functions, but they lack a function name; they are, essentially, function literals that are passed to other methods or objects, and cannot be called directly, due to the lack of a name. Here’s a fairly typical line of jQuery code, illustrating the use of anonymous functions:

                	
$(document).ready(function() {
	console.log(‘document is ready!’);
});
					
				

In this case, the anonymous function is passed as a callback function (that is, a function to be executed later, when a certain condition is met - in this case, the document being fully loaded or “ready”). This function has no real purpose besides being executed when the document is ready - so not having a name is fine. You could pass a named function, as a variable, into the document ready callback as well, if you felt there was value in being able to call the function from other parts of your program.

Being able to pass a function as a function argument is an example of JavaScript’s support for first-class functions - that is, functions being treated just like any other variable. This is a powerful paradigm that allows for expressive syntax and powerful programming capacity.

Here’s an example of passing a named function to the jQuery ready callback:

                	
function whenReady() {
	console.log(‘document is ready’);
}

//when the document is ready, the whenReady function will be called
$(document).ready(whenReady);
					
                

Finally, if you need to create a function that take multiple arguments, it’s simple enough - just separate the multiple arguments by commas in the function definition, like so:

                	
function manyArgs(a, b, c) {
	return (a + b + c);
}
               		
                

JavaScript Objects

Objects in JavaScript are somewhat different than typical objects in OOP (Object-Oriented Programming) languages. They boil down to being object literals and containers for key/value pairs. Object literals are declared once and only exist as one instance, the literal. Upon hearing this, you might be tempted to believe that JavaScript objects are really like underpowered structs, only containing data, and also lacking the capacity for instantiation - but remember, in JavaScript, there are first-class functions - which means for any given key in an object, there can be a value of a function. This allows for methods in object literals.

What is genuinely different about objects in JavaScript is that there is no “class” keyword, allowing you to define a class once and instantiate many objects of that type. There are ways to get around this and use JavaScript’s prototypal OOP style to create many objects from a prototype - but first, let’s learn about object literals.

Here’s an example of a JavaScript object literal:

                    	
myObj = {
    a: 1,
    b: {
        inner1: 21,
        inner2: 42
    },
    c: function() {
        console.log(‘in c function’);
    }
}
						
                    

This example has three key/value pairs. The first has an integer value, the second has an object value, which in turn holds a set of key/value pairs. The third outer key, “c”, has a value of a function. This function can be reached and executed by calling “myObj.c()”. In this way, JavaScript objects do have “methods”, however, they still lack the ability to be instantiated.

To access the inner object in the “b” key in “myObj”, you would type “myObj.b.inner1” or “myObj.b.inner2”.

There’s another way to create new objects - by initializing them as a new Object, like so:

                    	
var myNewObj = new Object();
						
                    

Now, you can add properties to the object, even a method that returns one of the properties:

                    	
var myNewObj = new Object();
myNewObj.a = 5;
myNewObj.b = "test";
//this property is actually a function, which returns the value of property “b”
myNewObj.c = function() { return this.b};

alert(myNewObj.c());
						
					

If you want to create objects that can be instantiated, there is a somewhat acceptable solution attainable through the use of prototypes and constructors. When you create an object using the “new Object()” method, you’re building an object from the “Object” prototype. Here’s a basic example of a custom prototype, and a constructor function:

                    	
MyClass.prototype = {
	printFib: function() {
		console.log(‘1, 1, 2, 3, 5, 8’);
}
	sum: function(a, b) {
		return a + b;
	},
	constructor: MyClass
}

function MyClass(initVal) {
	this.internalVal = initVal;
}

						
					

This code establishes the functions in a “MyClass” object: “printFib” and “sum”. It also describes the constructor for “MyClass” objects; in the constructor, the property “internalVal” is set to the “initVal” argument of the constructor.

Now, when you want to create an instance of the “MyClass” prototype, you just use the “new” keyword, like so:

                    	
OneOfMyClasses = new MyClass(‘50’);
						
                    

Now, OneOfMyClasses will have the two functions from the MyClass prototype, along with the value 50 in its property “internalVal”, courtesy of the constructor function.

JavaScript DOM Tutorial

So far, we’ve covered the core JavaScript language. The reality of front-end web development is that JavaScript is a tool used in the browser - and the DOM is the interface provided by the browser, allowing JavaScript to affect the document, window, and the site in general. We’ll start by looking at the document object, which represents the web page’s content.

The DOM has a suite of functions for getting elements by their id, tag name, or class name - though getting elements by class name is not supported in some older browsers.

If you want to retrieve a DOM element by its id, you can use the getElementById() method:

                	
var myElement = document.getElementById(‘mainDiv’);
					
				

This will retrieve the DOM node that has an id of “mainDiv”. Now that we have a DOM node, we can set various properties of that node, including the CSS styles, attributes, and HTML content.

                	
myElement.style.width = ‘300px’;
myElement.style.height = ‘300px’;
myElement.style.backgroundColor = ‘black’;
myElement.style.border = ‘5px solid green’;
					
                

Note how CSS properties that are more than one word are in “camel case” format - that is, no spaces, and each word other than the first word starts with a capital letter. This is the correct syntax for working with CSS properties through DOM commands.

Suppose we were manipulating an image tag, rather than a div - we could set the alt and src attributes using DOM commands:

                	
var myImg = document.getElementById(‘myImageTag’);
myImg.alt = ‘a nice image’;
myImg.src = ‘images/nice_image.jpg’;
					
				

Sometimes, retrieving an element by id is not the optimal way to operate. Certain elements might not have id attributes, or it might be an unintuitive way to go about retreiving the DOM node. There are two other DOM methods available to us: getElementsByTagName, which retrieves all elements with a certain tag name, and getElementsByClassName, which retrieves all elements with a given class name.

Here’s an example of chaining these commands together to really zoom in on a specific DOM node:

                	
var myId = document.getElementById(‘outerDiv’);
var myTableRows = myId.getElementsByTagName(‘tr’);
var myClassTd = myTableRows.getElementsByClassName(‘imageColumn’);
					
				

This code finds the element with id “outerDiv”, then zooms in on the table rows under that div, and finally selects the table data elements that are in the “imageColumn”class.

If you want to alter the HTML inside of an element, there is a command for that - “innerHTML”. Simply type a DOM node, such as “myDiv”, followed by “innerHTML =” and then type your HTML code:

                	
myDiv = document.getElementById(‘thisDiv’);
myDiv.innerHTML = ‘Test Link’;
					
                

You can also retreive the HTML of an object by calling the innerHTML method on an element, like so:

                	
console.log(myDiv.innerHTML);
					
				

The topics in this tutorial on the JavaScript DOM represent a lot of the functionality available to JavaScript programmers. There are a few more objects besides the “document” object that I hope to cover in a later tutorial.