Master JavaScript Concepts
Master JavaScript Concepts
*Disclaimer*
Everyone learns at their pace.
www.bosscoderacademy.com 1
Javascript
JavaScript is the scripting language of the Web.
Introduction to JavaScript
JavaScript is used in millions of Web pages to improve the design,
validate forms, detect browsers, create cookies, and much more.
www.bosscoderacademy.com 2
JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a
scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages >
www.bosscoderacademy.com 3
JavaScript Variables
Variables are "containers" for storing information.
A variable's value can change during the execution of a script. You can
refer to a variable by its name to display or change its value.
<html>
<script type= " text/javascript " >
var firstname;
firstname= " Welcome" ;
document.write(firstname) ;
document.write(" <br " ) ;
document.write(firstname) ;
</script>
<p>The script above declares a variable, assigns a value to it, displays
the value, change the value, and displays the value again. </p>
</html>
www.bosscoderacademy.com 4
Welcome XYZ
var x;
var carname;
After the declaration shown above, the variables are empty (they have
no values yet).
However, you can also assign values to the variables when you
declare them:
var x=5;
var carname="Scorpio";
After the execution of the statements above, the variable x will hold
the value 5, and carname will hold the value Scorpio.
Note: When you assign a text value to a variable, use quotes around
the value.
www.bosscoderacademy.com 5
Assigning Values to Undeclared JavaScript
Variables
If you assign values to variables that have not yet been declared,
the variables will automatically be declared.
These statements:
x=5;
carname="Scorpio";
var x=5;
var carname="Scorpio";
var x=5;
var x;
After the execution of the statements above, the variable x will still
have the value of 5. The value of x is not reset (or cleared) when you
redeclare it.
www.bosscoderacademy.com 6
DataTypes
B Numbers - are values that can be processed and calculated. You
don't enclose them in quotation marks. The numbers can be either
positive or negative. 5
B Strings - are a series of letters and numbers enclosed in quotation
marks. JavaScript uses the string literally; it doesn't process it.
You'll use strings for text you want displayed or values you want
passed along. 5
B Boolean (true/false) - lets you evaluate whether a condition meets
or does not meet specified criteria. 5
B Null - is an empty value. null is not the same as 0 -- 0 is a real,
calculable number, whereas null is the absence of any value.
TYPE EXAMPLE
www.bosscoderacademy.com 7
JavaScript Arithmetic
y=x-5;
z=y+5;
JavaScript Operators
y=5;
z=2;
x=y+z;
www.bosscoderacademy.com 8
JavaScript Arithmetic Operators
Given that y=5, the table below explains the arithmetic operators:
www.bosscoderacademy.com 9
JavaScript Assignment Operators
Given that x=10 and y=5, the table below explains the assignment
operators:
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
www.bosscoderacademy.com 10
After the execution of the statements above, the variable txt3
contains "What a verynice day".
To add a space between the two strings, insert a space into one of
the strings:
txt2="nice day";
txt3=txt1+txt2;
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
www.bosscoderacademy.com 11
Adding Strings and Numbers
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
www.bosscoderacademy.com 12
Comparison Operators
Given that x=5, the table below explains the comparison operators:
You will learn more about the use of conditional statements in the
next chapter of this tutorial.
www.bosscoderacademy.com 13
Logical Operators
Given that x=6 and y=3, the table below explains the logical
operators:
Conditional Operator
Example
greeting=(visitor=="PRES")?"Dear President
":"Dear ";
If the variable visitor has the value of "PRES", then the variable
greeting will be assigned the value
www.bosscoderacademy.com 14
Conditional Statements
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional statements
in your code to do this.
If Statement
You should use the if statement if you want to execute some code
only if a specified condition is true.
Syntax
if (condition)
www.bosscoderacademy.com 15
Example 1
<script type="text/javascript">
var time=d.getHours();
if (time<10)
{ document.write("Good morning");
</script>
Example 2
<script type="text/javascript">
var time=d.getHours();
if (time==11)
document.write("<b>Lunch-time!</b>");
</script>
www.bosscoderacademy.com 16
Note: When comparing variables you must always use two equals
signs next to each other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to
execute some code only if the specified condition is true.
If...else Statement
Syntax
if (condition)
else
www.bosscoderacademy.com 17
Example
<script type="text/javascript">
{ document.write("Good morning!");
else
document.write("Good day!");
</script>
www.bosscoderacademy.com 18
If...else if...else Statement
You should use the if....else if...else statement if you want to select
one of many sets of lines to execute.
Syntax
if (condition1)
else if (condition2)
else
www.bosscoderacademy.com 19
Example
<script type="text/javascript">
if (time<10)
document.write("<b>Good morning</b>");
document.write("<b>Good day</b>");
else
document.write("Hello World!");
</script>
www.bosscoderacademy.com 20
The JavaScript Switch Statement
You should use the switch statement if you want to select one of
many blocks of code to be executed.
Syntax
switch(n)
case 1:
break;
case 2:
break;
default:
code to be executed if n is
The value of the expression is then compared with the values for
each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the
code from running into the next case automatically.
www.bosscoderacademy.com 21
Example
<script type="text/javascript">
theDay=d.getDay();
switch (theDay)
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
</script>
www.bosscoderacademy.com 22
JavaScript Controlling
(Looping) Statements
Loops in JavaScript are used to execute the same block of code a
specified number of times or while a specified condition is true.
JavaScript Loops
Very often when you write code, you want the same block of code
to run over and over again in a row.
The for loop is used when you know in advance how many times
the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
code to be executed
www.bosscoderacademy.com 23
Example
Explanation: The example below defines a loop that starts with i=0.
The loop will continue to run as long as i is less than, or equal to 10.
i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <=
could be any comparing statement.
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i4+)
document.write("The number is
document.write("<br />");
</script>
</body>
</html>
www.bosscoderacademy.com 24
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
www.bosscoderacademy.com 25
JavaScript While Loop
Loops in JavaScript are used to execute the same block of code a
The while loop is used when you want the loop to execute and
Syntax
while (var<=endvalue)
code to be executed
Example
Explanation: The example below defines a loop that starts with i=0.
The loop will continue to run as long as i is less than, or equal to 10.
Example
<html>
<body>
<script type="text/javascript">
var i=0;
www.bosscoderacademy.com 26
while (i<=10)
document.write("<br />");
i=i+1;
</script>
</body>
</html>
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
Result www.bosscoderacademy.com 27
The do...while Loop
The do...while loop is a variant of the while loop. This loop will
always execute a block of code ONCE, and then it will repeat the
loop as long as the specified condition is true. This loop will always
be executed at least once, even if the condition is false, because
the code is executed before the condition is tested.
do
code to be executed
while (var<=endvalue);
Example
<html>
<body>
<script type="text/javascript">
var i=();
do
document.write("The number is
document.write("<br />");
i=i+l;
www.bosscoderacademy.com 28
while (i<0);
</script>
</body>
</html>
Result
The number is 0
www.bosscoderacademy.com 29
JavaScript Break and
Continue
There are two special statements that can be used inside loops:
break and continue.
There are two special statements that can be used inside loops:
break and continue.
Break
The break command will break the loop and continue executing the
code that follows after the loop (if any).
Syntax
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
if (i==3)
break;
www.bosscoderacademy.com 30
document.write("The number is " + i);
document.write("<br />");
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
Continue
The continue command will break the current loop and continue
with the next value.
Example
<html>
<body>
<script
var i=()
for
www.bosscoderacademy.com 31
if
continue;
number is
document.write("<br />");
</script>
</body>
</html>
Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
www.bosscoderacademy.com 32
JavaScript Functions
A function (also known as a method) is a self-contained piece of
code that performs a particular "function". You can recognise a
function by its format - it's a piece of descriptive text, followed by
open and close brackets.
To keep the browser from executing a script when the page loads,
you can put your script into a function.
You may call a function from anywhere within the page (or even
from other pages if the function is embedded in an external .js file).
Syntax
<html>
<head>
<script type="text/javascript">
function displaymessage()
alert("Hello World!");
www.bosscoderacademy.com 33
</script>
</head>
<body>
<form>
onclick="displaymessage()" >
</form>
</body>
</html>
If the line: alert("Hello world!!") in the example above had not been
put within a function, it would have been executed as soon as the
line was loaded. Now, the script is not executed before the user hits
the button. We have added an onClick event to the button that will
execute the function displaymessage() when the button is clicked.
www.bosscoderacademy.com 34
How to Define a Function
some code
var1, var2, etc are variables or values passed into the function. The
{ and the } defines the start and end of the function.
function functionname()
some code
www.bosscoderacademy.com 35
The return Statement
So, functions that are going to return a value must use the return
statement.
x=a*b;
return x;
}
When you call the function above, you must pass along two
parameters:
product=prod(2,3);
The returned value from the prod() function is 6, and it will be
stored in the variable called product.
www.bosscoderacademy.com 36
The Lifetime of JavaScript Variables
When you declare a variable within a function, the variable can only
be accessed within that function.
www.bosscoderacademy.com 37
What is an Event?
Event Handlers
The Event Handler for a Click event at a form field button element is
quite simple to understand:
www.bosscoderacademy.com 38
The event_handler_code portion of this example is any valid
JavaScript and it will be executed when the
There are "three different ways" that Event Handlers can be used to
trigger Events or Functions.
You can use an Event Handler located within an <A HREF= > tag to
make either an image or a text link respond to a mouseover Event.
Just enclose the image or text string between the <A HREF= > and
the </A> tags.
You can use these events to affect what the user sees on a page.
Here's an example of how to use link events. Try it out, View
Source, and we'll go over it.
<A HREF="javascript:void(")"
onClick="open('index.htm', 'links',
'height=2()O,width=20()');">How to Use Link Events
</A>
www.bosscoderacademy.com 39
The first interesting thing is that there are no <SCRIPT> tags. That's
because anything that appears in the quotes of an onClick or an
onMouseOver is automatically interpreted as JavaScript. In fact,
because semicolons mark the end of statements allowing you to
write entire JavaScripts in one line, you can fit an entire JavaScript
program between the quotes of an onClick. It'd be ugly, but you
could do it.
www.bosscoderacademy.com 40
<A HREF="javascript:void(")" tells the browser not to go
anywhere - it "deadens" the link when you click on it.
HREF="javascript: is the way to call a function when a link
(hyperlink or an HREFed image) is clicked
HREF="javascript:alert('Ooo, do it again!')" here we kill two
birds with one stone. The default behavior ofa hyperlink is to
click on it. By clicking on the link we call the window Method
alert() and also at the same time "deaden" the link.
The next line is
<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">
</A>
This is just like the first line, but it uses an onMouseOver instead of
an onClick.
Method 2 (Actions within FORMs):
</FORM>
www.bosscoderacademy.com 41
While any JavaScript statement, methods, or functions can appear
inside the quotation marks of an Event Handler, typically, the
JavaScript script that makes up the Event Handler is actually a call
to a function defined in the header of the document or a single
JavaScript command. Essentially, though, anything that appears
inside a command block (inside curly braces {}) can appear
between the quotation marks.
For instance, if you have a form with a text field and want to call the
function checkField() whenever the value of the text field changes,
you can define your text field as follows:
<INPUT TYPE="text" onChange="checkField(this)">
Nonetheless, the entire code for the function could appear in
quotation marks rather than a function call:
<INPUT TYPE="text" onChange="if (this.value <= 5) {
}">
To separate multiple commands in an Event Handler, use
semicolons
<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);
www.bosscoderacademy.com 42
Method 3 (BODY onLoad & onUnLoad):
<SCRIPT>
function doit() {
</SCRIPT>
-- OR --
<FORM>
-- OR --
www.bosscoderacademy.com 43
<INPUT TYPE="button" VALUE="Press Me"
-- OR --
</FORM>
</BODY>
The onLoad Event Handler is executed when the document or
frameset is fully loaded, which means that all images have been
downloaded and displayed, all subframes have loaded, any Java
Applets and Plugins (Navigator) have started running, and so on.
The onUnLoad Event Handler is executed just before the page is
unloaded, which occurs when the browser is about to move on to a
new page. Be aware that when you are working with multiple
frames, there is no guarantee of the order in which the onLoad
Event Handler is invoked for the various frames, except that the
Event Handlers for the parent frame is invoked after the Event
Handlers of all its children frames -- This will be discussed in detail
in Week 8.
Setting the bgColor Property
The first example allows the user to change the color by clicking
buttons, while the second example allows you to change colors by
using drop down boxes.
www.bosscoderacademy.com 44
Event Handlers
Given that y=5, the table below explains the arithmetic operators:
EVENT Description
www.bosscoderacademy.com 45
Note: Input focus refers to the act of clicking on or in a form
element or field. This can be done by clicking in a text field or by
tabbing between text fields.
www.bosscoderacademy.com 46
JavaScript Arrays
An array object is used to create a database-like structure within a
script. Grouping data points (array elements) together makes it
easier to access and use the data in a script. There are methods of
accessing actual databases (which are beyond the scope of this
series) but here we're talking about small amounts of data.
Name of
An array can be viewed like a
myCar column of data in a spreadsheet.
the array
0 Chev The name of the array would be
the same as the name of the
1 Ford column. Each piece of data
2 Buick Data (element) in the array is referred to
by a number (index), just like a row
3 Lincoln number in a column.
4 Truck An array is an object. Earlier, I said
Index
that an object is a thing, a
number collection of properties (array
Comparison of an array to elements, in this case) grouped
a column of data together.
You can name an array using the same format as a variable, a
function or an object. Remember our basic rules: The first
character cannot be a number, you cannot use a reserved word,
and you cannot use spaces. Also, be sure to remember that the
name of the array object is capitalized, e.g. Array.
This would mean that we are looking for data located in the array
starts at "0," this would actually be the fifth index. For instance, in
Array("Chev","Ford","Buick","Lincoln","Truck");
need to specify the size of the array. Sometimes, though, you may
That would pre-size the array with 20 elements. You might pre-size
www.bosscoderacademy.com 48
Multidimensional Arrays
This type of an array is similar to parallel arrays. In a
multidimensional array, instead of creating two or more arrays in
tandem as we did with the parallel array, we create an array with
several levels or "dimensions." Remember our example of a
spreadsheet with rows and columns? This time, however, we have a
couple more columns.
parameters
0 Gibson Les Paul Sunburst
1 Fender Stratocaster Black
Data
2 Martin D-28 Mahoaonv
3 Take mine EG330SC Saruce
Index number (objects created as arrays)
Comparison of a multidimensional array to a column of data
www.bosscoderacademy.com 49
emailList[3] = new Array("Sales Manager", "Bob Lark",
"blark@domain.com");
Second element of the main array third element of the second element
www.bosscoderacademy.com 50
You could also retrieve the information using something like:
www.bosscoderacademy.com 51
Array Properties
length
bannerImg[0]="image-1.gif";
bannerImg[1]="image-2.gif";
bannerImg[2]="image-3.gif";
var newBanner = 0
function cycleBan() {
newBanner++
if (newBanner == totalBan) {
newBanner = 0
document.banner.src=bannerImg[newBanner]
setTimeout("cycleBan()", 3*1000)
window.onload=cycleBan;
displayed:
www.bosscoderacademy.com 52
Let's take a look and see what happened here:
,: On the first line, we created a new instance of the array
bannerImg, and gave it three data elements. (Remember, we are
only making a copy of the Array object here.5
: Next, we created two variables: newBanner, which has a
beginning value of zero; and totalBan, which returns the length
of the array (the total number of elements contained in the
array):
: Then we created a function named cycleBan. This function will
be used to create a loop to cycle the images.
a. We set the newBanner variable to be increased each time the
function cycles. (Review: By placing the increment operator [" ++
"] after the variable [the "operand"], the variable is incremented
only after it returns its current value to the script. For example, its
beginning value is "0", so in the first cycle it will return a value of
"0" to the script and then its value will be increased by "1".)
www.bosscoderacademy.com 53
d. We then used the setTimeout function to tell the script how
long to display each image. This is always measured in
milliseconds so, in this case, the function cycleBan is called
every 3,000 milliseconds (i.e., every 3 seconds).
C9 Finally, we used the window.onload statement to execute the
function cycleBan as soon as the document is loaded.
There are a total of five properties for the Array object. In addition
to the length property listed above, the others are:m
SX constructor: Specifies the function that creates an object's
prototype9
NX index: Only applies to JavaScript arrays created by a regular
expression match9
FX input: Only applies to JavaScript arrays created by a regular
expression match9
xX prototype: Used to add properties or methods.
The other properties listed here are either more advanced or
seldom used. For now, we'll stick to the basics.
www.bosscoderacademy.com 54
Javascript Object Hierarchy
Hierarchy Objects
Object Properties Methods Event Handlers
www.bosscoderacademy.com 55
Object Properties Methods Event Handlers
www.bosscoderacademy.com 56
Object Properties Methods Event Handlers
Built-in Objects
www.bosscoderacademy.com 57
Object Properties Methods Event Handlers
www.bosscoderacademy.com 58
JavaScript Array Object
The Array object is used to store multiple values in a
single variable.
Create an Array
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
www.bosscoderacademy.com 59
2.
var myCars=new Array("Saab","Volvo","BMW");
document.write(myCars[0]);
Saab
myCars[0]="Opel";
www.bosscoderacademy.com 60
document.write(myCars[0]);
Opel
www.bosscoderacademy.com 61
JavaScript Date Object
Create a Date Object
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into
the future:
myDate.setDate(myDate.getDate()+5);
www.bosscoderacademy.com 62
Note: If adding five days to a date shifts the month or year, the
January 2010:
myDate.setFullYear(2010,0,14);
if (myDate>today)
else
www.bosscoderacademy.com 63
JavaScript Math Object
Math Object
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math
can be called by using Math as an object without creating it.
Mathematical Constants
Math.E
Math.PI
www.bosscoderacademy.com 64
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods
The following example uses the round() method of the Math object
to round a number to the nearest integer:
document.write(Math.round(4.7));
document.write(Math.random());
www.bosscoderacademy.com 65
The code above can result in the following output:
0.4218824567728053
document.write(Math.floor(Math.random()*11));
www.bosscoderacademy.com 66
JavaScript String Object
String object
Examples of use:
The following example uses the length property of the String object
to find the length of a string:
document.write(txt.length);
The code above can result in the following output:
12
The following example uses the toUpperCase() method of the
String object to convert a string to uppercase letters:
document.write(txt.toUpperCase());
www.bosscoderacademy.com 67
The code above will result in the following output:
HELLO WORLD!
www.bosscoderacademy.com 68
Why
Bosscoder?
1000+ Alumni placed at Top
Product-based companies.
Explore More