JavaScript for Journalists


JavaScript is a coding language used in webpages. It enables you to do things like add interactivity to a website, build applications, and retrieve data from other sites.

This tutorial is used as a reference guide to a class taught at the UC Berkeley Graduate School of Journalism on coding for journalists. It is recommended that this tutorial be used as a complement to a course on JavaScript and/or coding fundamentals.

Parts of a webpage

Webpages are made up of three elements:

  • HTML — The structure and content of the webpage.
  • CSS — The style and design of the webpage.
  • JavaScript — Code that enables things like interactivity or manipulation of elements on a webpage.

All three parts of a webpage are written in a unique syntax, and are considered different languages.

Where does JavaScript reside?

JavaScript is stored right inside the HTML of a webpage. The code itself is put in one of two places:

Linking to a JavaScript file

JavaScript can be stored in a separate text file that is referenced in your HTML. Generally, this separate text document has the file extension .js

The link to this JavaScript document can be placed anywhere in your HTML, but typically it appears in the <head> of your document so that it’s loaded quickly, and before the rest of your webpage. There are times when you want to load your JavaScript last, before the closing </body> tag. This helps to speed up the loading of your webpage, since the browser processes the code last. This is often done when the JavaScript code is not critical to the timing of the loading of the page.

JavaScript is included on a webpage using the <script> tag. To link to a javascript file, use the following syntax:

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

Javascript screenshot

It is important to note that when linking to JavaScript files, you need both an opening and closing <script> tag.

Inline JavaScript

JavaScript can also be written directly within the HTML of a webpage, also using the <script> tag. Put your code between the opening and closing script tags. However, you should omit the src=”” attribute from the “Linking to a JavaScript File” example above.

<script type="text/javascript">
	//JavaScript code here

It’s important to note that <script> tags can be used for more than just JavaScript code. So while the attribute type="text/javascript" is not required, but is good practice to use. There is a lot of debate on whether to use it, since some older browsers might intrepet differently. A plain <script> tag will also work, as all modern browsers automatically default to JavaScript language when the see a <script> tag with no attribute.

Noscript tags

While it’s not required, there is a special <noscript> tag in HTML which allows you to display content to users who use browsers that don’t support JavaScript, or who have JavaScript turned off. In recent years, there is less concern that browsers may not support JavaScript since virtually every browser today uses JavaScript (even mobile devices). This noscript feature is most often used for users of screen readers, like the blind, who browse the web with special software or devices that speak out the content of webpages. Noscript tags are a method of displaying some safety text, especially in situations when you are using JavaScript to manipulate the content of the page—which doesn’t happen when JavaScript is disabled.

<script type="text/javascript">
	document.write("Text that won't show up if a user has JavaScript 
	disabled in their browser.");

<noscript>Text that will show up if, and only if, a user has JavaScript 
disabled in their browser.</noscript>

Remember, the contents of a noscript tag won’t display for most users. Only those who are using a browser that has JavaScript disabled.


JavaScript is a lot like math in the sense that we store data in variables. Here is some info about variables, and how they work in JavaScript. Here are links to sections of this page:

Naming Variables
The VAR Keyword
Assignment Operator
Math Operations
String Data Type
Concatenating Strings with Numbers
Boolean Data Type
Assigning a Variable to Itself

Naming Variables

Variables in JavaScript must follow a certain set of naming rules.

  1. Variables must start with a letter*
  2. Variables can only contain letters, numbers or an underscore (a few other characters are permitted in special circumstances)
  3. Variables cannot have spaces
  4. Variables in JavaScript are case sensitive, which means the variable mytotal is a different variable than myTotal.

*there are some rare exceptions not addressed here.

Variable names can be a single letter, such as i, j or k. But it is better better to use more descriptive names such as total, sum or totalscore. You will come up with your own names for variables in your program which pertain to your own application.

The VAR keyword

When using variables in JavaScript, you should declare them using the VAR keyword. This establishes the word you picked to be used as a variable under a certain “scope,” or place. (more on what this means in the section on functions.)

var i
var total
var numberofphotos

Only use the var keyword the first time you mention a variable in any scope (space).

Assignment Operator

The expression:

var x = 7

means that we are storing the value 7 inside the variable x. It does not establish equivalency, instead the equals sign is performing a task of storing the value on the right inside the variable on the left.

It is also possible to replace the value of variable with something else. Thus the expression:

x = 7
x = 8
x = 9

means that x will be 9, the final value. Each time we assign a new value, it replaces the old value.

When a variable is assigned to another variable, it receives its value, as in this example:

x = 8
y = x

The value of y is 8. Because in the first line, we assigned 8 to the x variable. Then in the second line, we assigned the value of x, to y.

Math operations

In JavaScript, you can perform some basic arithmetic operations.

x = 5 + 7

The value of x will be 12. Likewise, you can use other variables for a part of these math operations.

x = 5
y = 2
j = x + y

In this case the value of j will be 7. You can also perform multiplcation and division, and even use parethesis much the same way you do with algebraic expressions. Multiplication is done with an asterisk (*), and division with a forward slash (/).

x = 9
y = (x / 4) * (x + 3)

The value of y is 27, or 9 divided by 4, multiplied by the sum of 9 and 3.


A semicolon terminates a line of code. Think of it similar to a period at the end of a sentence. Technically, semicolons are optional in JavaScript. The browser is smart enough to know that if there is a carriage return (new line,) the statement is automatically terminated. However, we still recommend using semicolons for clarity, and for certain situation where you may want to condense your code through a process called minifying. When using semicolons, you can put several statements on the same line, and the browser will know that they are separate statements.

var x = 7; var i = 10; var total = 22;

String Data Type

Variables can store more than numbers. They can also store words, phrases and several other types of abstract data. If you want to store a word or a phrase, you need to surround it by quotes. (both single or double quotes work.)

var myname = "Jeremy";
var website = "Knight Digital Media Center";

If you don’t use quotes, the browser will think you are trying assign values to another variable.


What happens with you try add two string variables? In JavaScript, it simply connects the two together in a process called concatenation.

firstname = "Jeremy";
lastname = "Rue";
fullname = firstname + lastname;

In the above example the value of fullname is JeremyRue. Notice there is no space. That is becauase JavaScript will concatenate variable exactly without the addition of spaces. Notice the following example:

sentence = "This tutorial is written by";
firstname = "Jeremy";
lastname = "Rue";
fullsentence = sentence + " " + firstname + " " + lastname;

In this example, the fullsentence variable will contain the string This tutorial is writtten by Jeremy Rue, with spaces between all words.

Concatenating strings with numbers

It is also possible to concatenate strings and number. The result will always be a string.

firstnumber = "4";
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber would be the string “45.” It’s important to understand when variables are numbers, and when they are strings of text that simply contain numbers. Taking the example above, if we didn’t have quotes around the 4, it would not concatenate the two values, but rather combine them.

firstnumber = 4;
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber is 9. Because the type of data in both of these variables are numbers, they are not concatenated, but rather combined as numbers.

Boolean Data Type

Variables in JavaScript can store much more than numbers and text strings. They can also store a wide array of abstract data types. One of these is the Boolean data type, which only has two values: true and false. Why we would want to store a true or false value in a variable doesn’t make a lot of sense right now. But later, in the section on conditionals, it becomes a vital tool.

var showtooltip = false;

Assigning a Variable to Itself

Sometimes you want to change the value of a variable, based on its current value. This often done by assigning a variable to itself, and applying the changes.

var x = 27;
x = x + 3;

In the above example, the value of x is now 30. When you assign a variable to itself, the value doesn’t change until the operation is complete. It is also possible to do this with strings, which concatenates the variable:

var fullname = "Jeremy";
fullname = fullname + " " + "Rue";

In the above example, the value of full name is Jeremy Rue. We first assign it the value Jeremy, then we assign the original value with the last name concatenated.


An array is a method of storing multiple values in a single variable.

var myarray = ["bob", "john", "peter", "sandy"];

Each value in an array is separated by a comma. The values can also have a unique data types. For example, some values can be numbers, while other values can be strings or booleans.

var myarray = ["joe", 47, false, true];

In order to retrieve any element in the array, we use something called the index number. It is important to note that the index of every array starts on zero.

var myarray = ["bob", "john", "peter", "sandy"];
console.log( myarray[2] );

In the above example, myarray[2] would retrieve the value “peter” because it is the third element in the array. (remember, we start on zero.) We can also cite the index in a number of ways. What are the values of the following variables?

var myarray = [
var x = 1;

myarray[ 1 + 2]

In the first example, myarray[1+2] would retrieve the “sandy” value, because it is the fourth element. In the second example, the myarray[x] would retrieve the “john” value, because it is the second element. This idea of being able to bring up a value becomes very useful later, especially when working with large datasets.

It’s also important to note how the array was typed out on multiple lines. JavaScript doesn’t care how the information is presented, as long as the opening and closing brackets match up correctly.

Changing Values Within an Array

You can change individual values within an array by referencing them by their index number. Consider the following:

var myarray = [

myarray[1] = "mary";

The “john” value no longer exists in myarray, because we’ve replaced it with “mary.” Remember, john was located at index 1, which is the second value because indices start on zero.

Multidimensional Arrays

A multidimensional array sounds more complicated than it is. The idea is simple: An array within an array. Sometimes the key to grasping a multidimensional array lies in how it’s typed out.

var my2Darray = [
	["bob", "alex", "joe", "wendy"],
	["teresa", "jodi", "sara", "peter"],
	["jack", 44, 90],
	[true, false]

The above array has four elements, each one is also an array. So how do we reference each item? We use indexes for both the main array, and each child array nested. For the above array:

my2Darray[0][1] //This would return "alex"
my2Darray[2][2] //This would return 90
my2Darray[3][0] //This would return true
my2Darray[2][3] //This is undefined, since there is no fourth element

We used the name 2D array because this is a two-dimensional array. It is possible to further have more arrays nested within these arrays, and so on. It begins to get very complex however. Generally, most arrays don’t go too far beyond three dimensions.

More ways to write arrays

Arrays can be typed and declared in a number of ways. If you want to declare a variable as an array without assigning any values to it, you have to use a special statement called a constructor. Here are two ways to do this:

var myarray = new Array();
var myarray = [];

These are both functionally the same thing. Once you’ve declared your array, it is possible to change out or assign specific values at various indices.

var myarray = [];
myarray[3] = "john";
myarray[2] = 56;
myarray[102] = "Peter";

If there was already a value in those spots, it would be replaced.

When you reference an array item, it works just like any other variable. You can concatenate them, or use them in arithmetic functions, like so:

var myarray = [1, 2, 3, 4, 5, 6, 7];
var sum = myarray[2] + myarray[4];

The value of sum would be 8, since we are adding the values 3 and 5. Remember, indices start on zero.

Test yourself:

var myarray = ["Java", "learned", "I", "today", "Script"];
var indices = [3, 2, 1, 0, 4];

What is the value of the variable message?

var message = myarray[indices[0]] + " " + 
	 myarray[indices[1]] + " " + 
	 myarray[indices[2]] + " " + 
	 myarray[indices[3]] + myarray[indices[4]];

In the above example, we actually use an array to represent the index value of each array.


Objects are variables that can store associative data and functions. Objects have a much larger role in JavaScript than just storing data, as we’ll find out later. But at this point in the tutorial we’ll learn about how to create a basic generic object— in our case mostly used for storing associative data.

There are three basic formats for writing objects:

  1. Object literal
  2. Dot notation
  3. Square bracket notation

Object Literals

An object literal is a method of writing an object. You cannot recall values from an object using a literal, only assign values.

An object literal is written with curly braces. Each item in the object contains an keyword called a property and it is separated by a colon with the value of that property.

var person = {name: "Jim", age: 47, location: "Berkeley"};

In the above example, we’ve created a variable called person, and we’ve associated three properties with this person; a name, age and location. Each property is assigned a value, with an according datatype.

Using Dot Notation To Create Objects

It is possible to create a generic object without assigning it a value. This is called instantiating, a process that will become more important later when we cover classes.

var dog = new Object();

Once we’ve instantiated an object, we can assign properties to it. = "Rex";
dog.type = "hound";
dog.age = 3;
dog.hasFleas = false;

It is important to note that this is another way of creating and assigning values to an object. We could achieve the same exact result with an object literal like so:

var dog = {name: "Rex", type: "hound", age: 3, hasFleas:false };

Using Square Bracket Notation to Create Objects

Square bracket notation is very similar to dot notation, and it offers a few advantages. The primary advantage is that property names can have spaces, since they are strings. This also allows us to calculate property names dynamically.

Like dot notation, we must first instantiate an object:

var cat = new Object();

Next, we assign properties to it.

cat["name"] = "Penny";
cat["type"] = "Tabby";
cat["age"] = 3;
cat["likes to sleep"] = true;

Take note of the last line of the above code. The property “likes to sleep” has spaces, so typing this as dot notation would not be possible.

Just as with dot notation, we can create this object using object literals. Below is the identical method of creating the cat variable using object literals:

var cat = {name : "Penny", type : "Tabby", age : 3, "likes to sleep": true };

Surrounding property names in quotes is usually optional in object literals, but it is required when property names have spaces.

Arrays and Objects

Arrays and objects work well together. They are very similar, but have some important differences. Objects use properties to identify values, while Arrays use an index number, to store multiple values.

In this following example, we have an array of office workers. Each item in the array is a different object that we can reference.

var officeWorkers = [ 
	{name: "Suzy", position: "secretary", "years of employment": 5},
	{name: "Jim", position: "manager", "years of employment": 2},
	{name: "Robert", position: "janitor", "years of employment": 10},
	{name: "Mary", position: "CEO", "years of employment": 1}

In the above array, if we wanted to reference any of the objects, we would first use the index of that object, then use the respective property name. For example, if we wanted to get Mary’s position we would reference that by one of two ways:


Either dot notation or square bracket notation can be used to recall information. Remember, object literals are only for assigning data, so we cannot use them to retrieve values from an object.

Advantages of using square bracket notation

Square bracket notation has benefits because we can dynamically create the property name. There are situations where we may wish to reference a property of an object in response to a particular action by the user, or for retrieving data from a very large dataset. Consider the following example:

var photos = {
	photo1: "fish.jpg",
	photo2: "cat.jpg",
	photo3: "dog.jpg",
	photo4: "horse.jpg",
	photo5: "turtle.jpg",

While we can retrieve any of these items using the properties (photo1, photo2, photo3, etc.) sometimes we may need to specify the property name based on another value.

var currentPhoto = 1;
photos["photo" + currentPhoto];

In the above situation, the information in the square bracket will resolve to photo1, and thus retrieving the information for “cat.jpg” in the photos variable. The reason this happens, is because we’ve concatenated the string “photo” with the value 1 in the variable currentPhoto, which was set earlier.

Objects inside of objects

Objects can be nested inside of other objects, and this is quite common practice. However, making the code legible is crucial to understanding the structure of the object. We generally use a mix of indentation and carriage returns (new lines) to make the code human-readable.

var blogData = {
	title : "Headline for my blog post",
	author : "Jeremy Rue",
	meta : {
		date : "Jan 1, 2012",
		time : "12:00am",
		keywords : "blog post berkeley"

In this above example, you can see that the value of the meta property is another object. Using both dot notation or square bracked notation, we could recall these values—such as the keywords property—like so:


JavaScript Object Notation, or JSON

There is a standard on the web for transferring information between websites called JavaScript Object Notation, or JSON (pronounced “jase-on.”) JSON is simply a combination of JavaScript object notation and arrays. JSON is used by many other programming languages than JavaScript, and has cemented itself as a standard format for data. This is why understanding objects, arrays and datatypes is so crucial for undestanding how JavaScript works.

Here is an example of some JSON formatted data:

    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    "phoneNumber": [
            "type": "home",
            "number": "212 555-1234"
            "type": "fax",
            "number": "646 555-4567"

It’s important to know that JSON is just the data. In its purest form, it’s not assigned to a variable. Many times JSON will be transferred in a way where it’s automatically encased in a function call, known as JSONP. This is often done to get around cross-browser security limitations.


One of the hallmarks of programming is the conditional operator. It gives the programs the ability to logically assess a variable, and decide a course of action depending on the result.

We use these operators to find out if a particular condition is true, and to pick a course of action depending on the result.

Conditinal operators use the keyword if to find out if a certain condition—which is surrounded in parenthesis—is true or false. If the condition is true, then code that is surrounded by curly brackets is executed. Here is an example:

var score = 5;

if(score == 10){
	document.write("Congratulations! you won");

In the above example, we are assessing the condition x == 10 to see if this is true. The double-equals symbols is the equivalency operator, and checks to see if both sides of the equation are equal. This is different than the single-equals symbol, which is the assignment operator, and performs a different action of assigning a value to a variable.

In the above example, the code within the curly brackets would not execute, because the value score is not 10, and the condition was not true. So, our program would skip over the code in the curly brackets.

Here are some possible operators that can be used to establish conditions:

Operator Description
== Equivalency Operator. Checks whether both sides are equal.
!= Bang Operator. Checks whether both sides are not equal.
> Greater than. Checks whether the left side is larger, but not equal to, the right side.
< Less than. Checks whether the left side is smaller, but not equal to, the right side.
>= Greater than or equal to. Checks whether the left side is greater or equal to right side.
<= Less than or equal to. Checks whether the left side is less than or equal to the right side.

Checking if value is more than or less than

In these examples, we check to see if the value is more than or less than another value. It’s important to note that all of these conditions will have either true or false result. If the condition is true, the code within the curly braces will be executed.

var x = 7;
var y = 10;

if(x > y){
	document.write("You win!");

In the above example, the value of x is not more than y, therefore, the code in the curly braces will not execute.

var age = 12;
var requirement = 12;

if(age >= requirement){
	document.write("You can ride the ferris wheel!");

In the above example, the code would be executed because the condition is true, age is more than or equal to the requirement variable.

Else Statement

Sometimes you want some code to execute on when a condition is not met. We can optionally provide an alternative action using the else keyword, and a second set of curly brackets. Observe the following example:

var age = 20;

if(age >= 21){
	document.write("Have a beer!");
} else {
	document.write("Sorry, have a juice box instead.");

In the example above, the age variable is 20, which does not meet the condition of being more than or equal to 21. So the code inside the first set of curly brackets will not execute. The else statment provides an alterative when the condition fails, or is false.

Negated Conditions

It’s important to remember that the program assesses the expression inside the parenthesis, to determine if it’s a true or false statement. This can be tricky at times, especially when using negated conditions. There is an operator called the not operator (also called a bang) that means “not equal to.” This is sometimes useful when you want to ensure the value can be anything but an equavalency. Observe the example below:

var answer = 3;

if(answer != 3.14){
	document.write("This is not pi");

In the above example, the expression evaluates to a true statement, answer is not equal 3.14, so the program will execute the code between the curly brackets.

Evaluating multiple conditions

There are times when you want to check if multiple conditions exist. JavaScript, and many other programming languages, offer two operators for determining if multiple conditions exist, the AND operator, and the OR operator. The AND operator is signified by two ampersands, like so &&. The OR operator is sigified by two bar or pipe keys, like so ||.

Symbol Description
&& AND operator. Checks if all conditions are true.
|| OR operator. Checks if either condition is true.

In the example below, we use the AND operator to check if two conditions are true.

var minimumHeight = 48;
var maximumHeight = 78;
var rider = 40;

if(rider > minimumHeight && rider < maximumHeight){
	document.write("you're tall enough to ride the ferris wheel");

In the example above, the code between the curly brackets will only execute if—and only if—both conditions are true. If one of them is false, the entire statement evaluates to false. The above example would not run, since the rider variable is not more than the minimumHeight, even through it is less than the maximumHeight.

The figure below shows and example using the OR operator:

var userResponse = "Maybe";

if(userReponse == "yes" || userResponse == "no"){
	document.write("Thanks for answering the question");
} else {
	document.write("Only yes or no responses are accepted");

In the example above, either condition can be true for the whole statement to be true. In situations where both conditions are true, the entire statement evaluates to true.

Below are some additional examples using the OR and AND operators:

if(x == 1 && y == 2 && z == 3){
	document.write("All three conditions must be true to see this text.");

if(x == 1 || y == 2 || z == 3){
	document.write("Any of the conditions can be true to see this text.");

Using Additional Parenthesis To Combine AND and OR operators

In situations where you want to use both AND and OR operators, you will need to specify the order of operations with additional parenthesis, like so:

if((x == 1 || x == 10) && (y == 1 || y == 6)){
	document.write("For this to be seen, x needs to be 1 or 10 and y
			needs to be 1 or 6.");

Empty Strings and Zero-value Numbers

There are a couple of idiosyncrasies to JavaScript and the way it assesses certain variables. If a string is empty, the variable it is assigned to will assess as false. Also, any number that has a zero value, will also result in a false condition when assessed. Consider the following example:

var emptyString = "";

if(emptyString == true){
	document.write("This text would only appear if the string had content.");
} else {
	document.write("Empty strings are false.");

The same is true of zero-value numbers, which will result as a false statement. It should also be noted that it is possible to assess a variable without using the equivalency operator. Putting a variable in the parenthesis will assess whether the variable is true or false. This is also a great method to check if a variable has a value.

var num = 10;
num = num - 10; //num is now zero

	document.write("This text won't display since
			num is zero, and false");
} else {
	document.write("This text will display, since 
			num is zero, and thus false.");

For Loops

Since we’ve mastered the concept of arrays, it’s important to learn how to use for-loops, which takes advantage of the index part of the array. As you recall, the index is the the part of the array that specifies which data element we want to retrieve.

var someArray[index];

There are times in which we want to repeat a piece of code over and over again. This is called a loop. Why do we want to repeat a piece of code? The most typical example of a loop is the ability to iterate through a large data set—like that of an array, changing or retrieving values. There are actuallyserveral different types of loops in JavaScript, four of them are:

  1. For Loop
  2. While Loop
  3. Do … While Loop
  4. For .. In Loop

Structure of a For Loop

The most common loop is the for-loop, which uses the For keyword. It is best to master the for-loop first before learning the others. In many cases, the for-loop can accomplish the same results as the others, but using more verbose language.

The for-loop consists of three parts. 1) A start value, 2) A condition and 3) An increment. Each is separated by semi-colons.

for(start value; condition; increment){
	//code that will be executed over and over

The for-loop is designed to count from the start value you set—while executing the code you specify—until the condition is met. It counts by increments you give in the third part of the expression. This is a basic example of the for loop:

for(var i=0; i < 20; i=i+1){
	//code will execute 20 times

In the above example, we set i = 0 as our start value. The variable we created, i, is also called the iterator because it iterates each time the loop is run. The for-loop will run the code between the curly braces as long as the condition i < 20 is true. Each time the code is run, the last part of the for-loop, called the increment will execute. In our case, we increment our variable by one each time using i = i + 1. When we are using the increment to increase the value by only 1, it is often typed shorthand using i++, which is a method of increasing any number variable by one.

Here is another example of using a for-loop:

for(var i=0; i < 5; i++){
	document.write("some text <br />");

some text
some text
some text
some text
some text

From the above example, you can see when we run the loop, it writes the text to the screen five times. In our for-loop, we initialized the i variable as zero, and we increment it by one until the condition i < 5 is met. Once the i variable hits five, the for loop terminates, and the rest of the program continues after it.

Using the Iterator in a For Loop

The iterator, or i variable, can be used within the loop, like so:

for(var i=0; i < 5; i++){
	document.write("The value of i is: " + i + " <br />");

The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4

As we see from the example above, the i variable increases by one each time. It starts on zero because that is what we specified during the first part of the for-loop. It never hits five, because our condition prohibits it.

Using the iterator is a powerful tool because it works as the index of an array.

var myarray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];

for(var i=0; i < 10; i++){


As we see above, we can use the i variable to reference each item in the array, and write it to the screen. It might not seem like it with this small example, but for-loops are powerful it terms of going through very large dataset, and quickly referencing hundreds, or thousands, of items.

We can also use the .length property to determine the length of an array dynamically. This allows us to set our condition in a way so that if items are ever added to the array, we don’t have to modify our for-loop.

var myarray = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];

for(var i=0; i < myarray.length; i++){

Changing the Increment or Start Values

Although it’s rare done, it is possible to change the increment in such a way that we step through the counter at different increments. Observe this example:

for(var i=0; i < 10; i += 2){
	document.write(i + "<br />");


In the above example, we increment i by two each time. This way, as it counts, it reaches the condition faster. We can also use the increment do decrease (or decrement) the value, like so:

for(var i=10; i &gt 0; i--){
	document.write(i + "<br />");


In the above example, we used the for-loop to count backwards. We also started the i variable at 10, and we changed our condition so that it was a true statement as long as the value of i was above zero. It isn’t often that we do this, but there are situations when this comes in handy.


A function is a block of code that is stored into memory to await execution at a time when the function is run. When we place code in a function, it is read by the program, but the code is not run immediately, but rather until we tell it to.

Functions in the examples below are given names that follow the same rules as variable names; no spaces or special characters (except underscores) and they are case-sensitive.

function myGreatFunction(){
	document.write("This will only be seen when the function is run");

In the above example, myGreatFunction stores some code that is setup to be run at a later time. A function is written starting with the keyword function in lowercase, followed by the function’s name. It is then proceeded by an opening and closing parenthesis. The body of the function, were the code is kept is surrounded by curly brackets.

You can run—or “call”— a function by referencing its name followed by parenthesis.

function myGreatFunction(){
	document.write("This will only be seen when the function is run");


This will only be seen when the function is run

One of the more common uses of functions is attaching them to events, like a mouse click. This way, we can run a block of code whenever a specific event occurs. Below is the <button> tag with a special attribute called onclick which will execute some JavaScript:

<button id="myButton" onclick="displayMessage()">Test this button</button>

function displayMessage(){
	document.write("You clicked the button!");

In the example above, you can see we’ve created a function called displayMessage. When the button is clicked, we execute the displayMessage function, displaying some text on the screen.

Passing Data into a Function

The parenthesis in a function play an optional, but important role in the power functions have in JavaScript. We can optionally put a variable in the parenthesis, which allows us to pass data into the function when it’s called. This allows us to reuse functions for many different purposes, and have them operate differently depending on what data is pass in.

function displayMessage(message){

displayMessage("Hello World" + "<br />");
displayMessage("Show me the money!");

Hello World
Show me the money!

In the example above, we’ve called the displayMessage function twice, but each time we sent the function a different string of data. That data was passed in the message variable, and made available to us within the function. The variable used to pass in data is called the argument. Arguments do not need to be declared with the VAR keyword. It is also worth noting that arguments are not available outside the function, and only exist within the function call. (More on this later.)

We also have the ability to send multiple arguments of data to a function. We do this by separating them with acomma.

function greeting(name, location){
	document.write("Hello " + name + " from " + location);

greeting("Jeremy", "Berkeley");

Hello Jeremy from Berkeley

Functions can also return data back to the place they were called. This is ideal in situations where we want to modify data quickly, and have it sent back. Observe the following example:

function addNumbers(num1, num2){
	var total = num1 + num2;
	return total;

document.write("7 plus 4 is " + addNumbers(7, 4));


In the above example, we called the function addNumbers and sent it two piece of data: 7 and 4. The function added the numbers, then sent back the total using the return keyword. It’s important to note that we created a new variable, total, inside this function using the VAR keyword. This variable only exists within the scope of this function. If we tried to reference it elsewhere, we would get an error message or an undefined.

Below is another working example of passing data into a function, and returning the message:

function makeBold(str){
	return "<strong>" + str + "</string>";

document.write("Some " + makeBold("text") + " where parts are " + makeBold("bold"));

Some text where parts are bold

In the above example, we’ve designed a function that takes a string, and adds some <strong> tags around them, then returns the new text. We can reuse the function over and over by sending new data, each time it would convert it to bold.

About this Tutorial

This tutorial was written by Jeremy Rue.

Republishing Policy

This content may not be republished in print or digital form without express written permission from Berkeley Advanced Media Institute. Please see our Content Redistribution Policy.

© 2020 The Regents of the University of California