Professional Documents
Culture Documents
05 April 2011
Want a foundational understanding of the JavaScript language? This article gets you started by
covering basic JavaScript concepts for beginners, and provides code examples to show how
it's all done.
View more content in this series
The JavaScript language has become increasingly popular and is arguably one of the most
prominent languages on the Internet. You can use it across various platforms and browsers,
and it does not discriminate against back-end languages. There are many different libraries
some that are greatto help with development, speeding up development time and so on. The
issue is that sometimes these libraries are so removed from the original language that beginning
developers lack an understanding of the language fundamentals. This article explains the
language fundamentals by covering basic JavaScript concepts to give beginners a foundational
understanding of the language. Code examples are provided throughout to show how it's all done.
Trademarks
Page 1 of 13
developerWorks
ibm.com/developerWorks/
Dynamically add, edit, and remove HTML elements and their values
Validate web forms before submission
Create cookies to store and retrieve data on a user's computer for future visits
Before getting started, there are just a few language basics to be aware of:
To include JavaScript code in an HTML file, you must place the code inside script tags and
include the text/javascript type attribute (Listing 1).
All JavaScript statements end with a semicolon.
The language is case sensitive.
All variable names must begin with a letter or underscore.
You can use comments to identify certain lines of your script. You write comments using a
double forward slash (//) followed by the comment.
You can also use comments to comment out script. A good way to comment out multiple lines
of script is by using /* your script goes here */. Any script within the stars /**/ doesn't
run during execution.
Listing 1. The script tags and type attribute are required to include JavaScript
code in an HTML file
<script type="text/javascript"></script>
To hide JavaScript code from browsers that do not support it or if a user has it turned off, simply
use the comment tag before and after the JavaScript statement (Listing 2).
Listing 2. Use comments to hide JavaScript code from browsers that do not
support it
<script type="text/javascript">
<!-Example statement here
//-->
</script>
The most commonly used way to include JavaScript code in a web page is to load it from an
external JavaScript file using the src attribute in the script tag (Listing 3).
External JavaScript files are the most common way to include JavaScript code for a number of
practical reasons:
Search engines can crawl and index your web site faster if there is less code within your
HTML page.
Keeping your JavaScript code separate from your HTML is cleaner and ultimately easier to
manage.
Because you can include multiple JavaScript files in your HTML code, you can separate the
JavaScript files into different folder structures on your web server, similar to images, which is
Get started with the JavaScript language, Part 1: JavaScript
language fundamentals
Page 2 of 13
ibm.com/developerWorks/
developerWorks
an easier way to manage your code. Clean, organized code is always key to easily managing
your website.
Variables
Variables store data that can later be retrieved or updated with new data. The data stored in a
variable can be a value or expression. There are three types of expressions in the JavaScript
language, which are described in Table 1.
Description
Arithmetic
Evaluates to a number
String
Evaluates to a string
Logical
There are two types of variables: local and global. You declare local variables using the var
keyword and global variables without using the var keyword. With the var keyword the variable
is considered local because it cannot be accessed anywhere outside the scope of the place you
declare it. For example, if you declare a local variable inside a function (which I cover toward the
end of this article), it cannot be accessed outside of that function, which makes it local to that
function. If you declare the same variable without the var keyword, it is accessible throughout the
entire script, not only within that function.
Listing 4 shows an example of a local variable, named num, which is assigned the value of 10.
To access the value of the num variable at another point in the script, you simply reference the
variable by name, as shown in Listing 5.
The result of this statement is "The value of num is 10." The document.write function writes data to
the web page. You will use this function throughout the rest of this article to write examples to the
web page.
To store arithmetic expressions in a variable, you simply assign the variable to the calculated
value as shown in Listing 6. The result of the calculation is what is stored in the variable, not the
calculation itself. Therefore, once again, the result is "The value of num is: 10."
Page 3 of 13
developerWorks
ibm.com/developerWorks/
To change the value of a variable, refer to the variable by the name you assigned to it and assign it
a new value using the equal sign (Listing 7). The difference this time is that you do not have to use
the var keyword because the variable has already been declared.
The result of this script is "The value of num is: 10" followed by "The new value of num is: 15."
In addition to teaching about variables, this section introduced the next topic, which is operators.
The equal sign (=), which you used to assign values to the variables, is an assignment operator,
and the plus sign (+), which you used to add 5 + 5, is an arithmetic operator. The next section talks
about all of the available operators in the JavaScript language and how you can use them.
Operators
You need operators when performing any operation in the JavaScript language. Operations include
addition, subtraction, comparison, and so on. There are four types of operators in the JavaScript
language:
Arithmetic
Assignment
Comparison
Logical
Arithmetic operators
Arithmetic operators perform basic mathematic operations such as addition, subtraction,
multiplication, division, and so on. Table 2 lists and describes all the arithmetic operators that are
available in the JavaScript language.
Description
Addition
Subtraction
Multiplication
Division
++
Increment
--
Decrement
Page 4 of 13
ibm.com/developerWorks/
developerWorks
Assignment operators
While arithmetic operators perform basic mathematic operations, assignment operators assign
values to JavaScript variables. You saw the most common assignment operator when you
assigned values to variables in the previous section. Table 3 lists and describes all the assignment
operators that are available in the JavaScript language.
Description
Equal
+=
-=
*=
/=
%=
You already saw how to use the equal sign to assign a value and expression to a variable, but now
I'll show you how to use one that can be a little more confusing. Assigning an addition value to a
variable can be a strange concept at first, but it's actually pretty simple (Listing 8).
The result of this script is "The value of num is: 10" followed by "The new value of num is: 15." You
can see that the operator in this script assigns the addition value to the variable. This can also be a
shorthand way of writing the script shown in Listing 9.
Comparison operators
Comparison operators determine the relationship between variables or their values. You use
comparison operators inside conditional statements to create logic by comparing variables or
their values to evaluate whether a statement is true or false. Table 4 lists and describes all the
comparison operators available in the JavaScript language.
Description
Page 5 of 13
developerWorks
ibm.com/developerWorks/
==
Equal to
===
!=
Not equal to
>
Greater than
<
Less than
>=
<=
Comparing variables and values is fundamental to writing any sort logic. The example in Listing 10
shows how to use the equal to comparison operator (==) to determine whether 10 is equal to 1.
Logical operators
Logical operators are generally used in conditional statements to combine comparison operators.
Table 5 lists and describes all the logical operators available in the JavaScript language.
Description
&&
AND
||
OR
NOT
Now that you have variables and operators under your belt, it's time to learn how to create
something with a little more storage than a simple variable.
Arrays
Arrays are similar to variables, but different in that they can hold multiple values and expressions
under one name. Storing multiple values in one variable is what makes arrays so powerful. There
is no limit to the amount or type of data that you can store in a JavaScript array and, as long as it
is within scope, you can access any value of any item in an array at any time after it is declared in
your script. While they can hold any data type in the JavaScript language, including other arrays, it
is most common to store similar data in any one array and to assign it a name that is related to the
items it contains. Listing 11 provides an example using two separate arrays to store similar data.
As you can see, while it may be possible to store all these items in one array, it isn't logical and
may cause problems later in the script, such as identifying what data is in the array.
Get started with the JavaScript language, Part 1: JavaScript
language fundamentals
Page 6 of 13
ibm.com/developerWorks/
developerWorks
Accessing values in an array is easy, but there is a catch. Arrays always start with an ID of 0,
rather than 1, which can be confusing when you're first getting started. The IDs then increment
from 0 on up, for example 0, 1, 2, 3, and so on. To access an array item you must use its ID, which
refers to the item's position in the array (Listing 12).
It is also possible to assign a value to a position in an array or update an item's value in an array,
just as you accessed an item in an array earlier (Listing 13).
Now you have a good understanding of variables, operators, and arrays. Next, start creating some
logic by putting what you've learned into action.
Conditional statements
Conditional statements are the backbone for creating any type of logic in a scripting or
programming language, and the JavaScript language is no exception. Conditional statements
determine what action to take based on the conditions you script. There are four ways to write
conditional statements in the JavaScript language, which are described in Table 6.
Description
if
if...else
if...else if...else
switch
Use the if statement if you only want to execute a script if a condition is true. Listing 14 shows
how to use an if statement with a comparison operator to execute a script if the condition is true.
Get started with the JavaScript language, Part 1: JavaScript
language fundamentals
Page 7 of 13
developerWorks
ibm.com/developerWorks/
Use the if...else statement if you want to execute one script if a condition is true or another
script if the condition is false, as shown in Listing 15.
Use the if...else if...else statement if there are different scripts that should execute based on
different conditions, as shown in Listing 16.
statements are different than if statements in that they cannot be used to determine
whether the value of a variable is greater or less than another value. Listing 17 shows an example
of when it is appropriate to use a switch statement to determine what script to execute.
Switch
Page 8 of 13
ibm.com/developerWorks/
developerWorks
You probably noticed the use of the case clause, break statement and default clause in Listing 17.
These clauses and statements are critical to the switch statement. The case clause determines
whether the value of switch is equal to the value of the data used in the case clause. The break
statement breaksor stopsthe switch statement from executing the rest of the statement.
And the default clause identifies a script that runs by default if none of the case statements are
executed or if the executed case statements do not have break statements. For example, Listing
18 shows how multiple case statements and the default statement can be executed if no break
statements are used in the executed case statements.
The result of this script is "num is equal to 10" followed by "num is: 10." This is sometimes called
switch fall-through.
As mentioned at the beginning of this section, conditional statements are the backbone of all logic
in any scripting or programming language, but without functions you have a tangled mess of code.
Functions
Functions are useful for a number of reasons. Functions are containers for script that is only to
be executed by an event or a call to the function. Therefore, functions do not execute when the
browser initially loads and executes the script that is included in a web page. The purpose of a
function is to contain script that has a task so that you then have the ability to execute that script
and run that task at any time.
Structuring a function is easy; it begins with the word function followed by a space and then
the name of the function. The name of the function can be anything you choose; however, it is
important to make it something that relates to the task it performs. Listing 19 shows an example of
a function that changes the value of an existing variable.
Page 9 of 13
developerWorks
ibm.com/developerWorks/
The example in Listing 19 not only shows how to structure a function, it also shows how to call
a function and change the value of a variable. You can change the variable value in this case
because the variable is declared within the scope of the main script, as is the function, so the
function is aware of the variable. However, if the variable is declared within the function you cannot
access it outside of the function.
Functions also have the ability to accept data through function parameters. Functions can have
one or more parameters, and a function call can have one or more arguments based on the
number of function parameters. It is common to confuse parameters and arguments; parameters
are part of the function definition, and arguments are expressions used when calling the function.
Listing 20 shows an example of a function that has parameters and a function call with arguments.
The function in this example increases the value of any argument passed to it. The argument in
this case is a variable that you have already declared. By passing it as an argument to the function
you are increasing its value to 11.
Return statements are also commonly used in functions. They return a value after executing
the script in a function. For example, you can assign the value that is returned by a function to a
variable. Listing 21 shows an example of how to return a value from a function after executing the
script.
The result of this script is "num is: 20." The benefit of this function is that it can add any two
numbers you pass to it and return a value that can be assigned to any variable, rather than always
changing the value of the same variable as in Listing 20.
Loops
As you've seen, arrays can be a great way to store a lot of reusable data, but that's just the starting
point; for and while loops provide functionality to iterate these arrays, access their values, and
execute script with them.
Get started with the JavaScript language, Part 1: JavaScript
language fundamentals
Page 10 of 13
ibm.com/developerWorks/
developerWorks
The most common loop type in the JavaScript language is the for loop. A for loop usually
consists of a variable that is assigned a numeric value, then that variable is used with a
comparison operator to compare it against another value, and, finally, the numeric value is
increased or decreased. The comparison in the for loop is typically determining whether the
numeric value of the initial variable is less than or greater than another numeric value. Then,
for the period of time that the condition is true, the loop runs and the variable is increased or
decreased until the condition evaluates to false. Listing 22 shows an example of how to write a for
loop that runs while a numeric value is less than the length of the array.
The length property of an array provides a numeric value that is equal to the number of items in
the array. Again, the trick is that the array starts with an ID of 0. Therefore, if there are 4 items in
an array, the length is 4, but the indices in the array are 0, 1, 2, and 3there is no 4.
Another type of loop is the while loop. They execute faster than for loops, but are appropriate
in cases other than iterating an array, such as executing a script while a certain condition is true.
Listing 23 shows how to write a while loop that executes a script while a numeric variable is less
than 10.
Notice that the script in the while loop includes a line that iterates the numeric variable until the
condition in the while loop is false. Without this line you would have an endless loop.
Conclusion
The JavaScript language is arguably one of the most popular languages, and now you can see
why. There are so many possibilities with this simple, but rich, scripting language. The fact that
it provides the tools to allow website visitors to interact with a web page after it downloads is
powerful. This article lays the foundation for understanding the fundamentals of the JavaScript
language. It should now be easier for you to understand how JavaScript libraries function and how
to use them to ease the process of writing client-side logic for your web pages. The next step is to
put these concepts into practice and also to begin exploring JavaScript objects.
Page 11 of 13
developerWorks
ibm.com/developerWorks/
Resources
Learn
Learn more about "JavaScript and the Document Object Model" (developerWorks, July
2002).
Read "Crossing borders: JavaScript's language features" (developerWorks, December 2006).
Dev Guru provides a comprehensive guide to the JavaScript language.
Learn more about the JavaScript language by reading "Classical Inheritance in JavaScript"
by Douglas Crockford.
Web development zone: The developerWorks Web development zone specializes in articles
covering various Web-based solutions.
Get products and technologies
When you achieve a fundamental understanding of the JavaScript language, the jQuery
library is a good way to speed up development.
Discuss
Create your developerWorks profile today and set up a watchlist on JavaScript. Get
connected and stay connected with developerWorks community.
Find other developerWorks members interested in Web development.
Share what you know: Join one of our developerWorks groups focused on Web topics.
Roland Barcia talks about Web 2.0 and middleware in his blog.
Follow developerWorks' members' shared bookmarks on Web topics.
Get answers quickly: Visit the Web 2.0 Apps forum.
Get answers quickly: Visit the Ajax forum.
Page 12 of 13
ibm.com/developerWorks/
developerWorks
Page 13 of 13