You are on page 1of 134

COURSE OUTLINE

The aim of this class is to teach beginners without any knowlege of JavaScript how to
use JavaScript directly. This will prepare beginners for libraries such as jQuery and
other real-life work with JavaScript..
1. Welcome to JavaScript
Exercise 1: Introduction to JavaScript
Exercise 2: Writing Javascript Code
Exercise 3: Writing Javascript Code :: Coding Conventions
Exercise 4: Write Javascript: the Script Element
Exercise 5: Javascript & DOM
2. JavaScript Alert Box & Math Rules
Exercise 1: Display messages with alert
Exercise 2: Math Rules: Order of operation math rules
Exercise 3: The Javascript Maths Object
3. Working With Variables, Strings & Prompt Dialog
Variables: Store data with variables
Prompt Box: Ask questions with prompt
Adding Strings: Joining strings and numbers with +
4. If Statements, Boolean values & Null values
Check user responses with if statements
Boolean values: true & false
Null value: The special value null
5. Confirm Command, Combining conditions & While loop
The confirm command
Combining conditions with && and ||
While loop: Repeat code with while loops
6. JavaScript Functions, Arrays & Dates
String functions in JavaScript
JavaScript Functions
Working With Arrays
Working With Dates
PRE-REQUISITES
This course requires you to have basic knowlege of HTML (HyperText Markup
Language) and to be able to create HTML pages with a plain text editor such as
notepad.
AN ALTERNATIVE JAVASCRIPT TESTER/DEBUGGER
There are many ways to run javascript, I created a special window-based editor that
can aid your learning javascript, it is free and can be downloaded from
http://sourceforge.net/projects/javascripteditor/

AUTHOR
This tutorial was brought to you by Anthony Ogundipe, you can find out more about
me by visiting http://www.dhtmlextreme.net or http://github.com/dhtml
Introduction to Javascript
Javascript has lots of uses, it is not only used to develop websites. This Javascript
Editor that was introduced in this tutorial is a windows
software, but javascript code was used in 95% of its development.
Javascript can also be used to develop games (you can check this link as an
example http://msdn.microsoft.com/en-us/library/windows/apps/hh465158.aspx).
Basic Facts:
Javascript is said to be the most popular language according to some sources. It is
also said by some to be the world's most misunderstood programming language.
I am however interested in technicalities since this is a practical section.
Here are some key facts about JavaScript:
1. Javascript has very little in common with Java, so being a Java guru does not
necessarily mean you will understand javascript (i use both languages so i know
this to be a fact).
2. JavaScript is an object oriented dynamic language: it has types and operators,
core objects, and methods. Its syntax comes from the Java and C languages, so
many structures from those languages apply to JavaScript as well.
3. JavaScript does not have classes; instead, the class functionality is accomplished
by object prototypes.
4. Javascript functions are objects, giving functions the capacity to hold executable
code and be passed around like any other object.
5. Javascript has lots of uses, it is not only used to develop websites. This Javascript
Editor that was introduced in this tutorial is a windows software, but javascript
code was used in 95% of its development.
6. Javascript is exclusively a client-sided language, this means that it must first be
downloaded from a server and then executed inside the browser. Unlike server-
sided scripts like PHP,PERL,JSP which are executed on the browser and the output
if any is sent to the client.
NEXT: Writing Javascript Code
< back to basics course outline
Writing Javascript Code
Javascript code is written as plain text, with a plain text editor
A simple javascript code is:
alert('Welcome to Javascript');
You can embed this code into a web page
various ways:
1. You can embed it into an html page directly
<html>
<head>
<title>Javascript Example</title>
<script>
alert('Welcome to Javascript');
</script>
</head>
<body>
My web page
</body>
</html>
2. You can embed it into an html page directly
<script>
alert('Welcome to Javascript');
</script>
3. You can put it inside an external file and link it to an html page indirectly
example.js
alert('Welcome to Javascript');
sample.html
<html>
<head>
<title>Javascript Example</title>
<script src='example.js'></script>
</head>
<body>
My web page
</body>
</html>
NEXT: Javascript Coding Conventions
< Introduction to Javascript
Javascript Coding Conventions
I am going to reference http://msdn.microsoft.com/en-us/library/ie/cte3c772
In this subsection, we are going to be looking at javascript as a programming
language. Most of the terminologies here will be explained as we delve more into the
language.
Like many other programming languages, JavaScript is organized into statements,
blocks consisting of related sets of statements, and comments. Within a statement
you can use variables, strings, numbers, and expressions.
A JavaScript program is a collection of statements. JavaScript statements
combine expressions in such a way that they carry out one complete task.
How to write statements in javascript
A statement consists of one or more expressions, keywords, or operators (symbols).
Typically, a statement is written on a single line, although a statement can be written
over two or more lines.
Also, two or more statements can be written on the same line by separating them
with semicolons. In general, each new line begins a
new statement. It is a good idea to terminate your statements explicitly. You do this
with the semicolon ( ; ), which is the JavaScript statement
termination character.
Here are two examples of JavaScript statements.
The sentences after the // characters are
comments, which are explanatory remarks in the
program.
var aBird = 'Robin'; // Assign the text "Robin" to the variable aBird.
var today = new Date(); // Assign today's date to the variable today.
A group of JavaScript statements surrounded by braces ({}) is called a
block.
Statements grouped into a block can generally be treated as a single statement. This
means you can use blocks in most places that JavaScript expects a single statement.
Notable exceptions include the headers of for and while loops. Notice that the single
statements within a block end in
semicolons, but the block itself does not.
An example script:
function inchestometers(inches)
{
if (inches < 0)
return -1;
else
{
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write('the value in meters is ' + meters);
This script is showing a combination of javascript statements. You can copy and paste
this code into the Javascript Editor to see the output.
You do not need to understand these codes yet, we are only introducing how the
codes are written.
NEXT: The Script Element
< Writing Javascript Code
The Script Element
When you want to use JavaScript on a website it has to be included within a SCRIPT
element:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JavaScript!</title>
</head>
<body>
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
</body>
</html>
The TYPE attribute should be set to 'text/javascript' or no TYPE attribute at all.
Linking to External Scripts
If you want to link to an external script file then simply add an SRC attribute to your
SCRIPT element corresponding to its location. It's normally a better idea to have
seperate script files than to write code inline as it means the browser can cache the
file. Plus you don't need to worry about any of that CDATA nonsense:
<script type="text/javascript" src="my-script.js"></script>
NEXT: Javascript & DOM
< Javascript Coding Conventions
Javascript & DOM
I think it will be good to introduce DOM at this point for reference sake, if you do not
understand all these, dont stress yourself, as the class goes on, we will make
references back to this and it will all make sense.
The Document Object Model, normally abbreviated to DOM, is the API (application
interface) through which JavaScript interacts with content within a website. JavaScript
and the DOM are usually seen as a single entity since JavaScript is most commonly
used for this purpose (interacting with content on the web). The DOM API is used to
access, traverse and manipulate HTML and XML documents.
The window object serves as the global object, you access it by just typing "window".
It's within this object that all of your JavaScript code is executed. Like all objects it
has properties and methods.
=> A property is a variable stored under an object. All variables created on a web-
page authomatically become properties of the window object.
=> A method is a function stored under an object. Since all functions are stored under
(at least) the window object they can all be referred to as 'methods'.
The DOM creates a hierarcy corresponding to the structure of each web document.
This hierarchy is made up of nodes. There are several different types of DOM nodes,
the most important are 'Element', 'Text' and 'Document'.
=> An 'Element' node represents an element within a page. So if you have a
paragraph element ('<p>') then it can be accessed through the DOM as a node.
=> A 'Text' node represents all text (within elements) within a page. So if your
paragraph has a bit of text in it can be directly accessed through the DOM.
=> The 'Document' node represents the entire document. (it's the root-node of the
DOM hierarchy/tree).
=> Also note that element attributes are DOM nodes themselves.
Most importantly: Each layout engine has a slightly different
implementation of the DOM standard. For example, the Firefox web
browser, which uses the Gecko layout engine, has quite a good
implementation (although, not entirely inline with the W3C specification)
but Internet Explorer, which uses the Trident layout engine is known for it's
buggy and incomplete implementation; a cause of much anguish within the
web development community!
And this explains why javascript behaves differently in different browsers,
this is the reason why libraries like jQuery are created to solve this problem
and to make javascript easier to use.
The images below show two different outlines of the typical DOM hierarchy
(Simplified)
DOM ILLUSTRATION 1: Flow Chart
DOM ILLUSTRATION 2: Tree View
NEXT: Display messages with alert
< The Script Element
Display messages with alert
An alert box is often used if you want to make sure information comes through to the
user. When an alert box pops up, the user will have to click "OK" to proceed.
Syntax: alert('message');
alternative syntaxes:
alert('message')
window.alert('message') // reference to current window
self.alert('message') // reference to current window
top.alert('message') // top-level frameset
parent.alert('message') // parent frame in a frameset
Examples:
alert('I am an alert box!');
NEXT: Math Rules: Order of operation math rules
< Javascript & DOM
Math Rules: Order of operation math rules
The simplest way I can explain how javascript handles mathematics is by
using the popular bodmas rules.
B -Brackets first
O - Orders (ie Powers and Square Roots, etc.)
DM - Division and Multiplication (left-to-right)
AS - Addition and Subtraction (left-to-right)
Using bodmas rules in javascript:
Example 1:
document.write(6 * (5 + 3)); //answer 48
Example 2:
document.write(2 + 5 * 3); //answer 17
Example 3:
document.write(30/5 * 3); //answer 18
Please note that the arithmetic sign for multiplication is (*) rather than (x).
Advanced learners: Javascript uses what we call the Operator Precedence, this means
that operators higher takes precedence (just like bodmas).
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
NEXT: The Javascript Maths Object
< Display messages with alert
The Javascript Maths Object
Math is a built-in object that has properties and methods for mathematical constants
and functions. Not a function object.
You can use it to perform other tasks such as get the value of PI (as in length of a
cycle 2*PI*R).
Example 1: Calculate the perimeter of a cycle with radius 16.
document.write(2 * Math.PI * 16); //answer 100.53096491487338
Example 2: Calculate the square root of 64
document.write(Math.sqrt(64)); //answer 8
Example 3: Calculate the sine of 90
document.write(Math.sin(90));
Example 4: Calculate the cosine of 90
document.write(Math.cos(90));
You can read more about the maths object here - https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Math
NEXT: Store Data With Variables
< Math Rules: Order of operation math rules
Store Data With Variables
I am going to use some w3school tutorials to illustrate variables to an extent.
JavaScript variables are "containers" for storing information.
You can test this out in the javascript editor.
var x = 5;
var y = 6;
var z = x + y;
alert(x);
alert(y);
alert(z);
You will get an alert with 5,6 and 11.
JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x = 5) or
expressions (z = x + y).
* Variable can have short names (like x and y) or more descriptive names (age, sum,
totalVolume).
* Variable names can contain letters, digits, underscores, and dollar signs.
* Variable names must begin with a letter
* Variable names can also begin with $ and _ (but we will not use it)
* Variable names are case sensitive (y and Y are different variables)
* Reserved words (like JavaScript keywords) cannot be used as variable names.
Javascript reserve keywords:
abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default,delete,do,double,else,enum
export,extends,false,final,finally,float,for,function,goto,if,implements,import,in,instanceof,int,interface,long,native,new,null,package,private,protected,
public,return,short,static,super,switch,synchronized,this,throw,throws,transient,true,try,typeof,var,void,volatile,while,with
NEXT: Prompt Box: Ask questions with prompt
< The Javascript Maths Object
Prompt Box: Ask questions with prompt
The Window.prompt() displays a dialog with an optional message
prompting the user to input some text.
Syntax: result = window.prompt(text, value);
* result is a string containing the text entered by the user, or the value null.
* text is a string of text to display to the user. This parameter is optional and can be
omitted if there is nothing to show in the prompt window.
* value is a string containing the default value displayed in the text input field. It is
an optional parameter. Note that in Internet Explorer 7 and 8, if you do not provide
this parameter, the string "undefined" is the default value
Example 1:
var sign = prompt('What is your sign?');
Example 2: enter scorpio as sign and see the resulting alert. If statement block shall
be treated in a later chapter.
var sign = prompt('What is your sign?');
if (sign == 'scorpio') {
alert('Wow! I am a Scorpio too!');
}
NEXT: Adding Strings: Joining strings and numbers with +
< Store Data With Variables
Adding Strings: Joining strings and numbers with +
Javascript handles strings and numbers in a different way that other languages.
Example 1: Let us join 2 strings together
var first='Tony';
var last='Ogundipe';
var result=first+last;
document.write(result); //result will be TonyOgundipe
Example 2: Let us join a string (tony) with a number (2014)
var name='Tony';
var year=2014;
var result=name+year;
document.write(result); //result will be Tony2014
NEXT: Check user responses with if statements
< Prompt Box: Ask questions with prompt
Exercise 1: Check user responses with if statements
One of the most important features of a computer language is the capability to test
and compare values. This allows your scripts to behave differently based on the
values of variables, or based on input from the user.
The if statement is the main conditional statement in JavaScript. This statement
means much the same in JavaScript as it does in Englishfor example, here is a
typical conditional statement in English:
If the phone rings, answer it.
This statement consists of two parts: a condition (If the phone rings) and an action
(answer it). The if statement in JavaScript works much the same way. Here is an
example of a basic if statement:
Example 1: this will not yield any result since the condition is not yet meth
if (a == 1) window.alert('Found a 1!');
This statement includes a condition (if a equals 1) and an action (display a message).
This statement checks the variable a and, if it has a value of 1, displays an alert
message. Otherwise, it does nothing.
If you use an if statement like the preceding example, you can use a single statement
as the action. You can also use multiple statements for the action by enclosing them
in braces ({}), as shown here:
Example 2: this will yield result because the condition was met initially.
var a=1;
if (a == 1) {
window.alert('Found a 1!');
a = 0;
}
This block of statements checks the variable a once again. If it finds a value of 1, it
displays a message and sets a back to 0.
Conditional Operators
While the action part of an if statement can include any of the JavaScript statements
you've already learned (and any others, for that matter), the condition part of the
statement uses its own syntax. This is called a conditional expression.
A conditional expression includes two values to be compared (in the preceding
example, the values were a and 1). These values can be variables, constants, or even
expressions in themselves.
Note:
Either side of the conditional expression can be a variable, a constant, or an
expression. You can compare a variable and a value, or compare two variables. (You
can compare two constants, but there's usually no reason to.)
Between the two values to be compared is a conditional operator. This operator tells
JavaScript how to compare the two values. For instance, the == operator is used to
test whether the two values are equal. A variety of conditional operators are
available:
Using Comparison Operators / Conditional Operators In Javascript
== (is equal to)
!= (is not equal to)
=== (equal value and equal type)
!== (not equal value or not equal type)
< (is less than)
> (is greater than)
>= (is greater than or equal to)
<= (is less than or equal to)
Example 3a: Note that x is an integer here
var x = 5;
if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 3b: Note that x is a string here
var x = '5';
if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}
Both will give the same result, however, using === which compares both values and
variable types, a different result will be seen
Example 4a: Note that x is an integer here
var x = 5;
if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 4b: Note that x is a string here
var x = '5';
if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 5: using comparison
var x=5,y=8;
if(x>y) {alert('x is greater than y');} else {alert('y is greater than x');}
Note:
Be sure not to confuse the equality operator (==) with the assignment operator (=),
even though they both might be read as "equals." Remember to use = when assigning
a value to a variable, and == when comparing values. Confusing these two is one of
the most common mistakes in JavaScript programming.
NEXT: Boolean values: true & false
< Joining strings and numbers with +
Exercise 2: Boolean values: true & false
Boolean logic is something used in most programming languages, including JavaScript.
It's very useful to know at least a little bit about it. In JavaScript, you mostly need it in
if() statements.
In Boolean logic, a statement can have two values, true or false. When using Boolean
logic in philosophy, the statement can be a sentence, like
It rains today.
In more down-to-earth applications like JavaScript, a statement is something like
x == 4
Both statements can be either true or false. When writing a program it is often
necessary to see if a statement is true or false. Usually this is done by an if()
statement. If the statement x == 4 is true, then do something:
if (x==4) {
do something
}
All this is not surprising. Boolean logic, however, also offers possibilities to evaluate a
whole string of statements and see whether the whole string is true or false. Like:
It rains today AND my feet are getting wet
In Boolean logic, this longer statement is true if it rains today is true AND my feet are
getting wet is true.
It rains today OR my feet are getting wet
In Boolean logic, this statement is true if it rains today is true OR if your feet are
getting wet is true OR if both statements are true.
This is also very useful when writing programs. For instance, suppose you want to do
something if x==4 OR y==1. Then you write:
if (x==4 || y==1) {
do something
}
The statement (x==4 || y==1) is true when x is 4 OR y is 1.
NEXT: Null value: The special value null
< Check user responses with if statements
Null value: The special value null
Javascript handles strings and numbers in a different way that other languages.
Example 1: Let us join 2 strings together
var first='Tony';
var last='Ogundipe';
var result=first+last;
document.write(result); //result will be TonyOgundipe
Example 2: Let us join a string (tony) with a number (2014)
var name='Tony';
var year=2014;
var result=name+year;
document.write(result); //result will be Tony2014
NEXT: The confirm command
< Boolean values: true & false
Exercise 1: The confirm command
This is used to confirm a user about certain action, and decide between two choices
depending on what the user chooses.
Syntax: window.confirm()
Note that the value x is a boolean value, the value will be TRUE if okay is clicked, and
FALSE when cancel is clicked.
Example:
var x=window.confirm('Are you sure you are ok?');
if (x)
window.alert('Good!');
else
window.alert('Too bad');
It can also be rewritten like this:
var x=window.confirm('Are you sure you are ok?');
if (x) {window.alert('Good!');}
else {window.alert('Too bad');}
or
var x=window.confirm('Are you sure you are ok?');
if (x==true) {window.alert('Good!');}
else {window.alert('Too bad');}
NEXT: Combining conditions with && and ||
< Null value: The special value null
Exercise 2: Combining conditions with && and ||
We have looked at the comparison operators above (>,<,==,=== etc), now, we
want to learn how to write more extended if statements using logical operators.
The Logical Operators are:
&& (and)
|| (or)
! (not)
Example 1: if either condition is true, the entire statement returns true
if ((20 > 500) || (50 < 200)) {
alert('20 is not greater than 500 but 50 is definitely less than 200');
}
Example 2: if both conditions are true, then the entire statement returns true
if ((20 > 500) && (50 < 200)) {
alert('Both conditions are not true, so this block will not execute');
}
Example 3: using not. Not causes reversal of conditions, i.e changes true to false and
false to true.
if ((20 != 500) && (50 != 200)) {
alert('20 is not 500 and 50 is not 200, so both statements are correct');
}
Example 4: this will not give any result
if ((20 != 20) && (50 != 200)) {
alert('this block will not run because 20 is 20 and cannot be anything else');
}
Javascript Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable
based on some condition.
Syntax: variablename = (condition) ? value1:value2
Consider this statement:
var age=15;
if(age<18) {var voteable='Too young';} else {var voteable='Old enough';}
alert(voteable);
it can be rewritten using the conditional operator as shown below with exactly the
same result:
var age=15;
var voteable = (age < 18) ? 'Too young':'Old enough';
alert(voteable);
NEXT: While loop: Repeat code with while loops
< The confirm command
While loop: Repeat code with while loops
Loops can execute a block of code as long as a specified condition is true.
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
code block to be executed
}
Example: this will iterate the value of i from 1 to 5.
var i=1;
while (i <= 5) {
alert(i);
i++;
}
There are more complicated ways of using while, but this will suffice for now and so
we end this tutorial.
NEXT: String functions in JavaScript
< Combining conditions with && and ||
Exercise 1: String functions in JavaScript
JavaScript has some very interesting internal string manipulation functions.
1. charAt(x): Returns the character at the x position within the string.
var myString = 'jQuery FTW!!!';
alert(myString.charAt(7)); //output: F
2. charCodeAt(x) Returns the Unicode value of the character at position x within
the string.
var message="jquery4u";
alert(message.charAt(1)); //alerts "q"
3. concat(v1, v2,) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
var message="Sam";
var final=message.concat(" is a"," hopeless romantic.");
alert(final); //alerts "Sam is a hopeless romantic."
4. fromCharCode(c1, c2,) Returns a string created by using the specified
sequence of Unicode values (arguments c1, c2 etc). Method of String object, not
String instance. For example: String.fromCharCode().
alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyz
alert(String.fromCharCode(72,69,76,76,79)); //output: HELLO
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. Start is
an optional argument specifying the position within string to begin the search. Default
is 0.
//indexOf(char/substring)
var sentence="Hi, my name is Sam!";
if (sentence.indexOf("Sam")!=-1) {
alert("Sam is in there!");
}
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of
the searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. Start is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
var myString = 'javascript rox';
alert(myString.lastIndexOf('r'));
//output: 11
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found.
//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;
var myNumber = '999';
var myInt = myNumber.match(intRegex);
alert(isInt);
//output: 999
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
alert(isInt); //output: null
8. replace(regexp/substr, replacetext) Searches and replaces the regular
expression (or sub string) portion (match) with the replaced text instead.
//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or
-1 if not found.
//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';
var isInt = myNumber.search(intRegex);
alert(isInt);
//output: 0

var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
alert(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the start and
end index arguments, NOT including the end index itself. End is optional, and if
none is specified, the slice includes all characters from start to end of string.
//slice(start, end)
var text="excellent";
alert(text.slice(0,4)); //returns "exce"
alert(text.slice(2,4)); //returns "ce"
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional limit is an
integer that lets you specify the maximum number of elements to return.
//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at start
and through the specified number of characters, length. Length is optional, and if
omitted, up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"
13. substring(from, [to]) Returns the characters in a string between from and
to indexes, NOT including to inself. To is optional, and if omitted, up to the end
of the string is assumed.
//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
alert(myString);
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to
lowercase.
//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
alert(myString)
//output: javascript rox
15. toUpperCase() Returns the string with all of its characters converted to
uppercase.
//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
alert(myString)
//output: JAVASCRIPT ROX
NEXT JavaScript Functions
< While loop: Repeat code with while loops
Exercise 1: String functions in JavaScript
JavaScript has some very interesting internal string manipulation functions.
1. charAt(x): Returns the character at the x position within the string.
var myString = 'jQuery FTW!!!';
alert(myString.charAt(7)); //output: F
2. charCodeAt(x) Returns the Unicode value of the character at position x within
the string.
var message="jquery4u";
alert(message.charAt(1)); //alerts "q"
3. concat(v1, v2,) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
var message="Sam";
var final=message.concat(" is a"," hopeless romantic.");
alert(final); //alerts "Sam is a hopeless romantic."
4. fromCharCode(c1, c2,) Returns a string created by using the specified
sequence of Unicode values (arguments c1, c2 etc). Method of String object, not
String instance. For example: String.fromCharCode().
alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyz
alert(String.fromCharCode(72,69,76,76,79)); //output: HELLO
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. Start is
an optional argument specifying the position within string to begin the search. Default
is 0.
//indexOf(char/substring)
var sentence="Hi, my name is Sam!";
if (sentence.indexOf("Sam")!=-1) {
alert("Sam is in there!");
}
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of
the searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. Start is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
var myString = 'javascript rox';
alert(myString.lastIndexOf('r'));
//output: 11
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found.
//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;
var myNumber = '999';
var myInt = myNumber.match(intRegex);
alert(isInt);
//output: 999
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
alert(isInt); //output: null
8. replace(regexp/substr, replacetext) Searches and replaces the regular
expression (or sub string) portion (match) with the replaced text instead.
//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or
-1 if not found.
//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';
var isInt = myNumber.search(intRegex);
alert(isInt);
//output: 0

var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
alert(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the start and
end index arguments, NOT including the end index itself. End is optional, and if
none is specified, the slice includes all characters from start to end of string.
//slice(start, end)
var text="excellent";
alert(text.slice(0,4)); //returns "exce"
alert(text.slice(2,4)); //returns "ce"
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional limit is an
integer that lets you specify the maximum number of elements to return.
//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at start
and through the specified number of characters, length. Length is optional, and if
omitted, up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"
13. substring(from, [to]) Returns the characters in a string between from and
to indexes, NOT including to inself. To is optional, and if omitted, up to the end
of the string is assumed.
//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
alert(myString);
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to
lowercase.
//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
alert(myString)
//output: javascript rox
15. toUpperCase() Returns the string with all of its characters converted to
uppercase.
//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
alert(myString)
//output: JAVASCRIPT ROX
Exercise 2: Creating JavaScript Functions
JavaScript also allows us to create custom functions to solve our everyday
functionalities. A custom function is a block of reusable code.
Let us create a function called hello which will just display an alert. Please note that in
the two examples below, you will not get any result because the functions were not
called and so will not be executed.
Example 1: creating the function
var hello = function () {
alert('i am saying hello');
};
Example 2:
function hello () {
alert('i am saying hello');
};
Example 3: executing the functions
var hello = function () {
alert('i am saying hello');
};
hello();
Example 4:
function hello () {
alert('i am saying hello');
};
hello();
The syntax of functions is shown below:
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
A function can have what we call arguments or parameters. Let us create a function
that will alert the first and last name of a person.
Example 5:
function myname(first,last) {
alert('Your full name is '+first+' '+last);
}
myname('Tony', 'Olawale');
Example 6: A function can also return a result
function myname(first,last) {
var r='Your full name is '+first+' '+last;
return r;
}
var fullname=myname('Tony', 'Olawale');
alert(fullname);
Exercise 3: Working With Arrays
An Array is an enumerated list of variables. It's a programming construct that allows
programmers to replace this
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
with this
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing
for easy looping through the data structure.
var x=[];
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
for(i=0; i<6; i++) {document.writeln(x[i]+'<br>');}
Which will output the following
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want
to create a new Array simply use brackets [] like this
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will
automatically increase the size of the Array as needed, as you add items into the
Array. Creating an Array with brackets instead of with thenew constructor avoids a bit
of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elemen
ts. var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add
more than one item then badArray would be initialized correctly since Javascript would
then be smart enough to know that you were initializing the array instead of stating
how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of
unintended results by using the new constructor, it's recommended you not use new
Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data
var myArray = ['January', 'February', 'March']; document.writeln('0>'+myArray[0]+'
<BR>'); // Will output: 0>January document.writeln('1>'+myArray[1]+'
<BR>'); // Will output: 1>February document.writeln('2>'+myArray[2]+
'<BR>'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[2] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>undefined document.writeln('3>'+myArray[3]+'<BR>'); // Will output:
3>undefined document.writeln('4>'+myArray[4]+'<BR>'); // Will outpu
t: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will out
put: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings,
functions, objects, other Arrays, even regular expressions
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]
; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 docu
ment.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! docum
ent.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.wr
iteln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.write
ln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln(
'4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension
arrays.
var x=[0,1,2,3,4,5]; var y=[x];
In the above example we created an array named x and assigned it as the first
element in the array y. If we ask for the value of y[0] it will return the contents of x as
a string because we didn't specify an index.
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance

document.writeln(bigArray[5][8][12][1])
would indicate bigArray's 5th index held an array, who's 8th index held an array,
who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; document.writeln(myArray
[1]); // Will output: one function passedByReference(refArray) { refArray[1] = '
changed'; } passedByReference(myArray); document.writeln(myArray[1]); // Wi
ll output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For
instance
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray;
newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray.slic
e(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: on
e function passedByReference(refArray) { refArray[1] = 'changed'; } passedB
yReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the
array. Since Arrays always start at zero, the length property is convenient for loops
since it will always be one greater than the actual index. For instance if the Array has
10 elements then the indexes will be 0-9, so as long as our counter is less than the
Array.length we'll cover the entire Array
for (var i=0; i<myArray.length; i++) {}
Going back to our undefined example above. Even though 3 of the Array items
are undefined the length property will still count them because it's always one higher
than the highest accessable index value.
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>Janua
ry document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February d
ocument.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined docu
ment.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined docume
nt.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined document.
writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March document.writeln(
'Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100
elements in an array and set the length to 50, Javascript will truncate the last 50
elements from the array (effectively deleting them). If you have 10 elements in an
array and set Array.length to 100 then the length of the array will be expanded to
100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = []; normalArray[1] = 'This is an enumerated array'; ale
rt(normalArray[1]); // outputs: This is an enumerated array var associativeArray
= []; associativeArray['person'] = 'John Smith'; alert(associativeArray
['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However All
arrays in Javascript are objects and Javascript's object syntax gives a basic emulation
of an associative Array. For this reason the example code above will actually work. Be
warned that this is not a real array and it has real pitfals if you try to use it. The
'person' element in the example becomes part of the Array object's properties and
methods, just like .length, .sort(), .splice(), and all the other built-in properties and
methods.
You can loop through an object's properties with the following loop
var associativeArray = []; associativeArray["one"] = "First"; associativeArray["two"
] = "Second"; associativeArray["three"] = "Third"; for (i in associativeArray) { d
ocument.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second,
three:Third };
In the above example, associativeArray.length will be zero because we didn't actually
put anything into the Array, we put it into associativeArray's
object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and
prototypes which have been added to the array and not just your data. A lot of
problems people have with the Prototype library is that their associative arrays break
because Prototype adds a few useful Prototype functions to the Array object and for i
in x loops pick up those additional methods. That's the pitfal of using Array/objects as
a poor man's associative array.
As a final example, the previous code will work regardless of whether you define
associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""),
or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are --
object properties, not Arrays.

Exercise 4: Working With Dates
Of all the core Javascript objects, I find Dates to be the most fascinating. Once you
learn a few small tricks everything about Javascript Dates just seem to fall into place
and you find that there's really nothing at all that you can't do with them, quickly, and
easily.
This reference will cover the Javascript Date Object, how it stores Dates, how you can
manipulate them, create calendars, countdown timers, prototype them to add your
own functionality, as well as provide a complete method reference.
Julian Dates
Julian Dates are a method of referencing time and dates based on how much time has
passed since an arbitrary number in the past. For instance, 215 days have presently
passed this year. If we know that January 1 begins on a Wednesday , then we know
that day 2 represents a Thursday in January. If we know there are 31 days in January
then we know that day 32 represents the first of February and we can figure out that
February 1st fell on a Saturday.
Javascript (and most languages) handle dates exactly as described above, only in
much grander fashion. Theepoch or starting point of Javascript's date system isn't
January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it
doesn't count just days! No Javascript counts the number of milliseconds that have
passed since January 1, 1970 and presently that number is 1,407,152,039,648.
Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers
indicate dates after 1970 and negative numbers indicate dates prior to 1970. For
instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript
counts in milliseconds and there are 1000 milliseconds in a single second so -1000
represents 1 second.
By a great coincidence Unix also uses January 1, 1970 as it's epoch date which means
a timestamp in Javascript will match a timestamp on your server as long as you take
some care with the timezones!
It will be quite a while before humanity has to worry about running out of dates!
Javascript can readily handle around 285,616 years on either side of the 1970 epoch.
Creating A New Date (Parsed)
To create a new Date all you have to do is to ask for one!
var myFirstDate = new Date();
This will create a new date object and since we did not specify a specific date or time,
the date will be equal to the instant it was created.
The Javascript Date Object has a very powerful date parser. While there are several
ways to create and set Dates. The one you're most likely to use is simply to specify
the date itself, as a string, when creating a new date.
var myDate = new Date('January 16, 1988');
Since we didn't specify a time the Date which is created will be for midnight in the
browser's timezone on January 16, 1988.
var myDate = new Date('January 16, 1988 2:54:16 pm');
Here we specify a specific time (note that there's a space between the time and pm).
Since we didn't specify a timezone the browser will use the user's timezone. We could
also have used millitary time (14:54:16).
Here we'll actually specify a time zone GMT in this case and below we'll print it out.
var myDate = new Date('January 16, 1988 2:54:16 pm GMT');
Sat Jan 16 1988 15:54:16 GMT+0100 (W. Central Africa Standard Time)
Unless you actually live in the Greenwich Mean Timezone, the date requested and the
date printed are unlikely to match. The created date is actually 2:54:16 in the GMT
timezone, however when we printed the date out, since we didn't specify anything
special, the date was printed in the Browser's time zone so the browser did a little
conversion for us to ensure the time we printed was the ACTUAL time relative to the
browser.
That's a little confusing so let's try for something different. Every New Years Eve, the
city of New York holds a big celebration and the ball is dropped at precisely midnight
in the eastern timezone. So lets create a date for that event.
var myDate = new Date('January 1, 2000 EST');
Since we didn't specify a time, Javascript will assume midnight for us, we did specify a
time zone so the actual time will be midnight in the eastern time zone.
Now when we print the date out we'll get that little timezone conversion and you can
see what time the ball will be dropping in your timezone! (of course people in the
eastern timezone will see the correct time).
Sat Jan 01 2000 06:00:00 GMT+0100 (W. Central Africa Standard Time)
Creating A New Date (arguments)
You can also create a new date by passing the date values as arugments to the Date
object. The arguments are Year, Month, Date and optionally hours, minutes, seconds,
and milliseconds. The first argument, year, is special. If it's a string the Date object
will try to parse it (see previous section), if it's a long integer it will try to use it as a
julian number. If there are more than one argument it will build the date from your
supplied arguments.
var d1 = new Date('January 1, 1970'); // Date as a parse
var d2 = new Date(0); // Date as a julian number
var d3 = new Date(1970, 0, 1); // Date as arguments
Notice we use zero as the month when creating d3, that's because Javascript months
go from 0 to 11 where January is zero. This is a pretty big gotcha if you're not careful!
The argument list is as follows
dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);
Working With Julian Day Numbers
Working with Julian Dates requires division and modulus. Division will discard the
portion of the date you no longer need and modulus (which is the remainder of
division) will return the portion of the date you are looking for.
Most people don't need milliseconds when doing date calculation, so we just divide
the Julian Date Number by 1,000. So if we have a Julian Day Number of
1,177,303,066,354 then dividing this by 1,000 will give us a day number of
1,177,303,066 -- a number which no longer holds information about the milliseconds
in the date.
To get the number of seconds this represents, we take the modulus of 60 because
there are 60 seconds in a minute.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
Now that we have the number of seconds we discard the seconds from the Julian date
by dividing it by 60.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
So now our day number has been stripped of milliseconds and seconds. We can find
out how many minutes the number represents by taking the modulus of 60 since there
are 60 minutes in an hour.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
And we can discard the minutes from the original number by dividing it by 60. What
remains are hours and days. We can get the hours by taking the modulus of 24 since
there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,
leaving only the number of days.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
dayNumber = dayNumber/60; // dayNumber = 327,028
var hours = dayNumber % 24; // hours = 4
dayNumber = dayNumber/24 // dayNumber = 13,626
Or 13,624 days between January 1, 1970 and Mon Apr 23 2007 05:37:46 GMT+0100
(W. Central Africa Standard Time)
Countdown Timers In Javascript
In the previous section we broke a day number out into its component milliseconds,
seconds, minutes, hours, and days. The number we used was the number of
milliseconds that had elapsed since January 1, 1970. But we could just as easily have
used another date. Lets take the difference between now and the end of the year.
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
This code creates two julian dates, now and newYear. By
subtracting now from newYear we get an integer which represents the difference
between the two dates, specifically: 12,914,813,502.
We can use division and modulus to extract the time from this number just like we did
in the previous section only now we're computing the difference between now and the
new year instead of a date and January 1, 1970.
This article is generating now and newYear in real-time so the values below are the
actual values until the new year!
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
This gives us a value of 149 Days, 11 hours, 26 minutes, 53 seconds, until Thu Jan 01
2015 00:00:00 GMT+0100 (W. Central Africa Standard Time).
Making a Timer
In the example above now is equal to the instant it is created while newYear is a
constant value, always equal to January 1 of next year. So it's actually very easy to
make a timer. All we have to do is turn the code above into a function, set up a
setTimeout command, and create a html division somewhere on the page to hold our
timer. Here's the new code!


<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyNewYear() {
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);

// We'll build a display string instead of doing document.writeln
var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
outStr+= ' minutes, ' + seconds + ' seconds until the new year!';
// Insert our display string into the countdown span.
document.getElementById('countdown').innerHTML=outStr;
// call this function again in exactly 1 second.
setTimeout("happyNewYear()",1000);
}
// call the countdown function (will start the timer)
happyNewYear();
</script>
When the function is called (every second), now is always set to the current, ever
advancing date, while the newYear always remains a constant. So the function works
to countdown the passing time to the destination date (new year).
And here's the result!
Does the time appear a bit off? Maybe because right now you're in Daylight time and
the new year is in daylight savings time! If this is the case, once everyone falls back
the timer will again be in sync with your expectations!
Making A Clock
Making a clock is very similar to making a countdown timer. All we have to do is to
create a new date and get it's hours, minutes, and seconds.
<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>
<script type="text/javascript">
function clock() {
var now = new Date();
var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
document.getElementById('clockDiv').innerHTML=outStr;
setTimeout('clock()',1000);
}
clock();
</script>
And the result (in military time):
Getting The Number Of Days In A Month
Javascript has a little quirk where a date of zero will set the date to be the last day of
the previous month. Likewise is there are 30 days in a month and you set a date of 31
it will be the 1st day of the next month, a date of 40 would be the 10th day of the
next month. This can lead to some very weird funkiness if you're not careful but we
can definitely exploit this for a useful prototype which will give us the number of days
in a specific month. We'll do this up as a prototype so it's available to all our Dates.
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
var d = new Date();
document.writeln('Number of days in this month: '+d.daysInMonth());
And the result (live!):
Getting The Name Of The Day And Month
While the Javascript Date Object has many useful features, one glaring oversight is
that when you ask it for the day or month it will return only the numerical
representation. This is easy enough to fix with prototypes however.
Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Mon
day', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; if (shortName) {
return Days[this.getDay()].substr(0,3); } else { return Days[this.getDay()];
} } Date.prototype.getMonthName = function() { return ['January', 'Februar
y', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'D
ecember'][this.getMonth()]; }
These two methods are pretty simple to use. If you want the month name just do
var d = new Date(); month = d.getMonthName();
If you want the name of the day, do
var d = new Date(); day = d.getDayName();
If you'd like the three character day name (mon/tue/wed, etc) then pass an argument
to getDayName. As long as the argument isn't false, null or any other falsey value the
name will be shortened to its three letter equivalent.
var d = new Date(); day = d.getDayName(true);
NEXT: Working With Arrays
< String functions in JavaScript
Exercise 1: String functions in JavaScript
JavaScript has some very interesting internal string manipulation functions.
1. charAt(x): Returns the character at the x position within the string.
var myString = 'jQuery FTW!!!';
alert(myString.charAt(7)); //output: F
2. charCodeAt(x) Returns the Unicode value of the character at position x within
the string.
var message="jquery4u";
alert(message.charAt(1)); //alerts "q"
3. concat(v1, v2,) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
var message="Sam";
var final=message.concat(" is a"," hopeless romantic.");
alert(final); //alerts "Sam is a hopeless romantic."
4. fromCharCode(c1, c2,) Returns a string created by using the specified
sequence of Unicode values (arguments c1, c2 etc). Method of String object, not
String instance. For example: String.fromCharCode().
alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyz
alert(String.fromCharCode(72,69,76,76,79)); //output: HELLO
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. Start is
an optional argument specifying the position within string to begin the search. Default
is 0.
//indexOf(char/substring)
var sentence="Hi, my name is Sam!";
if (sentence.indexOf("Sam")!=-1) {
alert("Sam is in there!");
}
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of
the searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. Start is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
var myString = 'javascript rox';
alert(myString.lastIndexOf('r'));
//output: 11
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found.
//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;
var myNumber = '999';
var myInt = myNumber.match(intRegex);
alert(isInt);
//output: 999
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
alert(isInt); //output: null
8. replace(regexp/substr, replacetext) Searches and replaces the regular
expression (or sub string) portion (match) with the replaced text instead.
//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or
-1 if not found.
//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';
var isInt = myNumber.search(intRegex);
alert(isInt);
//output: 0

var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
alert(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the start and
end index arguments, NOT including the end index itself. End is optional, and if
none is specified, the slice includes all characters from start to end of string.
//slice(start, end)
var text="excellent";
alert(text.slice(0,4)); //returns "exce"
alert(text.slice(2,4)); //returns "ce"
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional limit is an
integer that lets you specify the maximum number of elements to return.
//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at start
and through the specified number of characters, length. Length is optional, and if
omitted, up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"
13. substring(from, [to]) Returns the characters in a string between from and
to indexes, NOT including to inself. To is optional, and if omitted, up to the end
of the string is assumed.
//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
alert(myString);
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to
lowercase.
//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
alert(myString)
//output: javascript rox
15. toUpperCase() Returns the string with all of its characters converted to
uppercase.
//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
alert(myString)
//output: JAVASCRIPT ROX
Exercise 2: Creating JavaScript Functions
JavaScript also allows us to create custom functions to solve our everyday
functionalities. A custom function is a block of reusable code.
Let us create a function called hello which will just display an alert. Please note that in
the two examples below, you will not get any result because the functions were not
called and so will not be executed.
Example 1: creating the function
var hello = function () {
alert('i am saying hello');
};
Example 2:
function hello () {
alert('i am saying hello');
};
Example 3: executing the functions
var hello = function () {
alert('i am saying hello');
};
hello();
Example 4:
function hello () {
alert('i am saying hello');
};
hello();
The syntax of functions is shown below:
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
A function can have what we call arguments or parameters. Let us create a function
that will alert the first and last name of a person.
Example 5:
function myname(first,last) {
alert('Your full name is '+first+' '+last);
}
myname('Tony', 'Olawale');
Example 6: A function can also return a result
function myname(first,last) {
var r='Your full name is '+first+' '+last;
return r;
}
var fullname=myname('Tony', 'Olawale');
alert(fullname);
Exercise 3: Working With Arrays
An Array is an enumerated list of variables. It's a programming construct that allows
programmers to replace this
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
with this
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing
for easy looping through the data structure.
var x=[];
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
for(i=0; i<6; i++) {document.writeln(x[i]+'<br>');}
Which will output the following
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want
to create a new Array simply use brackets [] like this
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will
automatically increase the size of the Array as needed, as you add items into the
Array. Creating an Array with brackets instead of with thenew constructor avoids a bit
of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elemen
ts. var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add
more than one item then badArray would be initialized correctly since Javascript would
then be smart enough to know that you were initializing the array instead of stating
how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of
unintended results by using the new constructor, it's recommended you not use new
Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data
var myArray = ['January', 'February', 'March']; document.writeln('0>'+myArray[0]+'
<BR>'); // Will output: 0>January document.writeln('1>'+myArray[1]+'
<BR>'); // Will output: 1>February document.writeln('2>'+myArray[2]+
'<BR>'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[2] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>undefined document.writeln('3>'+myArray[3]+'<BR>'); // Will output:
3>undefined document.writeln('4>'+myArray[4]+'<BR>'); // Will outpu
t: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will out
put: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings,
functions, objects, other Arrays, even regular expressions
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]
; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 docu
ment.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! docum
ent.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.wr
iteln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.write
ln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln(
'4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension
arrays.
var x=[0,1,2,3,4,5]; var y=[x];
In the above example we created an array named x and assigned it as the first
element in the array y. If we ask for the value of y[0] it will return the contents of x as
a string because we didn't specify an index.
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance

document.writeln(bigArray[5][8][12][1])
would indicate bigArray's 5th index held an array, who's 8th index held an array,
who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; document.writeln(myArray
[1]); // Will output: one function passedByReference(refArray) { refArray[1] = '
changed'; } passedByReference(myArray); document.writeln(myArray[1]); // Wi
ll output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For
instance
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray;
newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray.slic
e(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: on
e function passedByReference(refArray) { refArray[1] = 'changed'; } passedB
yReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the
array. Since Arrays always start at zero, the length property is convenient for loops
since it will always be one greater than the actual index. For instance if the Array has
10 elements then the indexes will be 0-9, so as long as our counter is less than the
Array.length we'll cover the entire Array
for (var i=0; i<myArray.length; i++) {}
Going back to our undefined example above. Even though 3 of the Array items
are undefined the length property will still count them because it's always one higher
than the highest accessable index value.
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>Janua
ry document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February d
ocument.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined docu
ment.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined docume
nt.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined document.
writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March document.writeln(
'Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100
elements in an array and set the length to 50, Javascript will truncate the last 50
elements from the array (effectively deleting them). If you have 10 elements in an
array and set Array.length to 100 then the length of the array will be expanded to
100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = []; normalArray[1] = 'This is an enumerated array'; ale
rt(normalArray[1]); // outputs: This is an enumerated array var associativeArray
= []; associativeArray['person'] = 'John Smith'; alert(associativeArray
['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However All
arrays in Javascript are objects and Javascript's object syntax gives a basic emulation
of an associative Array. For this reason the example code above will actually work. Be
warned that this is not a real array and it has real pitfals if you try to use it. The
'person' element in the example becomes part of the Array object's properties and
methods, just like .length, .sort(), .splice(), and all the other built-in properties and
methods.
You can loop through an object's properties with the following loop
var associativeArray = []; associativeArray["one"] = "First"; associativeArray["two"
] = "Second"; associativeArray["three"] = "Third"; for (i in associativeArray) { d
ocument.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second,
three:Third };
In the above example, associativeArray.length will be zero because we didn't actually
put anything into the Array, we put it into associativeArray's
object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and
prototypes which have been added to the array and not just your data. A lot of
problems people have with the Prototype library is that their associative arrays break
because Prototype adds a few useful Prototype functions to the Array object and for i
in x loops pick up those additional methods. That's the pitfal of using Array/objects as
a poor man's associative array.
As a final example, the previous code will work regardless of whether you define
associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""),
or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are --
object properties, not Arrays.

Exercise 4: Working With Dates
Of all the core Javascript objects, I find Dates to be the most fascinating. Once you
learn a few small tricks everything about Javascript Dates just seem to fall into place
and you find that there's really nothing at all that you can't do with them, quickly, and
easily.
This reference will cover the Javascript Date Object, how it stores Dates, how you can
manipulate them, create calendars, countdown timers, prototype them to add your
own functionality, as well as provide a complete method reference.
Julian Dates
Julian Dates are a method of referencing time and dates based on how much time has
passed since an arbitrary number in the past. For instance, 215 days have presently
passed this year. If we know that January 1 begins on a Wednesday , then we know
that day 2 represents a Thursday in January. If we know there are 31 days in January
then we know that day 32 represents the first of February and we can figure out that
February 1st fell on a Saturday.
Javascript (and most languages) handle dates exactly as described above, only in
much grander fashion. Theepoch or starting point of Javascript's date system isn't
January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it
doesn't count just days! No Javascript counts the number of milliseconds that have
passed since January 1, 1970 and presently that number is 1,407,152,039,648.
Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers
indicate dates after 1970 and negative numbers indicate dates prior to 1970. For
instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript
counts in milliseconds and there are 1000 milliseconds in a single second so -1000
represents 1 second.
By a great coincidence Unix also uses January 1, 1970 as it's epoch date which means
a timestamp in Javascript will match a timestamp on your server as long as you take
some care with the timezones!
It will be quite a while before humanity has to worry about running out of dates!
Javascript can readily handle around 285,616 years on either side of the 1970 epoch.
Creating A New Date (Parsed)
To create a new Date all you have to do is to ask for one!
var myFirstDate = new Date();
This will create a new date object and since we did not specify a specific date or time,
the date will be equal to the instant it was created.
The Javascript Date Object has a very powerful date parser. While there are several
ways to create and set Dates. The one you're most likely to use is simply to specify
the date itself, as a string, when creating a new date.
var myDate = new Date('January 16, 1988');
Since we didn't specify a time the Date which is created will be for midnight in the
browser's timezone on January 16, 1988.
var myDate = new Date('January 16, 1988 2:54:16 pm');
Here we specify a specific time (note that there's a space between the time and pm).
Since we didn't specify a timezone the browser will use the user's timezone. We could
also have used millitary time (14:54:16).
Here we'll actually specify a time zone GMT in this case and below we'll print it out.
var myDate = new Date('January 16, 1988 2:54:16 pm GMT');
Sat Jan 16 1988 15:54:16 GMT+0100 (W. Central Africa Standard Time)
Unless you actually live in the Greenwich Mean Timezone, the date requested and the
date printed are unlikely to match. The created date is actually 2:54:16 in the GMT
timezone, however when we printed the date out, since we didn't specify anything
special, the date was printed in the Browser's time zone so the browser did a little
conversion for us to ensure the time we printed was the ACTUAL time relative to the
browser.
That's a little confusing so let's try for something different. Every New Years Eve, the
city of New York holds a big celebration and the ball is dropped at precisely midnight
in the eastern timezone. So lets create a date for that event.
var myDate = new Date('January 1, 2000 EST');
Since we didn't specify a time, Javascript will assume midnight for us, we did specify a
time zone so the actual time will be midnight in the eastern time zone.
Now when we print the date out we'll get that little timezone conversion and you can
see what time the ball will be dropping in your timezone! (of course people in the
eastern timezone will see the correct time).
Sat Jan 01 2000 06:00:00 GMT+0100 (W. Central Africa Standard Time)
Creating A New Date (arguments)
You can also create a new date by passing the date values as arugments to the Date
object. The arguments are Year, Month, Date and optionally hours, minutes, seconds,
and milliseconds. The first argument, year, is special. If it's a string the Date object
will try to parse it (see previous section), if it's a long integer it will try to use it as a
julian number. If there are more than one argument it will build the date from your
supplied arguments.
var d1 = new Date('January 1, 1970'); // Date as a parse
var d2 = new Date(0); // Date as a julian number
var d3 = new Date(1970, 0, 1); // Date as arguments
Notice we use zero as the month when creating d3, that's because Javascript months
go from 0 to 11 where January is zero. This is a pretty big gotcha if you're not careful!
The argument list is as follows
dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);
Working With Julian Day Numbers
Working with Julian Dates requires division and modulus. Division will discard the
portion of the date you no longer need and modulus (which is the remainder of
division) will return the portion of the date you are looking for.
Most people don't need milliseconds when doing date calculation, so we just divide
the Julian Date Number by 1,000. So if we have a Julian Day Number of
1,177,303,066,354 then dividing this by 1,000 will give us a day number of
1,177,303,066 -- a number which no longer holds information about the milliseconds
in the date.
To get the number of seconds this represents, we take the modulus of 60 because
there are 60 seconds in a minute.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
Now that we have the number of seconds we discard the seconds from the Julian date
by dividing it by 60.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
So now our day number has been stripped of milliseconds and seconds. We can find
out how many minutes the number represents by taking the modulus of 60 since there
are 60 minutes in an hour.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
And we can discard the minutes from the original number by dividing it by 60. What
remains are hours and days. We can get the hours by taking the modulus of 24 since
there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,
leaving only the number of days.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
dayNumber = dayNumber/60; // dayNumber = 327,028
var hours = dayNumber % 24; // hours = 4
dayNumber = dayNumber/24 // dayNumber = 13,626
Or 13,624 days between January 1, 1970 and Mon Apr 23 2007 05:37:46 GMT+0100
(W. Central Africa Standard Time)
Countdown Timers In Javascript
In the previous section we broke a day number out into its component milliseconds,
seconds, minutes, hours, and days. The number we used was the number of
milliseconds that had elapsed since January 1, 1970. But we could just as easily have
used another date. Lets take the difference between now and the end of the year.
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
This code creates two julian dates, now and newYear. By
subtracting now from newYear we get an integer which represents the difference
between the two dates, specifically: 12,914,813,502.
We can use division and modulus to extract the time from this number just like we did
in the previous section only now we're computing the difference between now and the
new year instead of a date and January 1, 1970.
This article is generating now and newYear in real-time so the values below are the
actual values until the new year!
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
This gives us a value of 149 Days, 11 hours, 26 minutes, 53 seconds, until Thu Jan 01
2015 00:00:00 GMT+0100 (W. Central Africa Standard Time).
Making a Timer
In the example above now is equal to the instant it is created while newYear is a
constant value, always equal to January 1 of next year. So it's actually very easy to
make a timer. All we have to do is turn the code above into a function, set up a
setTimeout command, and create a html division somewhere on the page to hold our
timer. Here's the new code!


<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyNewYear() {
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);

// We'll build a display string instead of doing document.writeln
var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
outStr+= ' minutes, ' + seconds + ' seconds until the new year!';
// Insert our display string into the countdown span.
document.getElementById('countdown').innerHTML=outStr;
// call this function again in exactly 1 second.
setTimeout("happyNewYear()",1000);
}
// call the countdown function (will start the timer)
happyNewYear();
</script>
When the function is called (every second), now is always set to the current, ever
advancing date, while the newYear always remains a constant. So the function works
to countdown the passing time to the destination date (new year).
And here's the result!
Does the time appear a bit off? Maybe because right now you're in Daylight time and
the new year is in daylight savings time! If this is the case, once everyone falls back
the timer will again be in sync with your expectations!
Making A Clock
Making a clock is very similar to making a countdown timer. All we have to do is to
create a new date and get it's hours, minutes, and seconds.
<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>
<script type="text/javascript">
function clock() {
var now = new Date();
var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
document.getElementById('clockDiv').innerHTML=outStr;
setTimeout('clock()',1000);
}
clock();
</script>
And the result (in military time):
Getting The Number Of Days In A Month
Javascript has a little quirk where a date of zero will set the date to be the last day of
the previous month. Likewise is there are 30 days in a month and you set a date of 31
it will be the 1st day of the next month, a date of 40 would be the 10th day of the
next month. This can lead to some very weird funkiness if you're not careful but we
can definitely exploit this for a useful prototype which will give us the number of days
in a specific month. We'll do this up as a prototype so it's available to all our Dates.
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
var d = new Date();
document.writeln('Number of days in this month: '+d.daysInMonth());
And the result (live!):
Getting The Name Of The Day And Month
While the Javascript Date Object has many useful features, one glaring oversight is
that when you ask it for the day or month it will return only the numerical
representation. This is easy enough to fix with prototypes however.
Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Mon
day', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; if (shortName) {
return Days[this.getDay()].substr(0,3); } else { return Days[this.getDay()];
} } Date.prototype.getMonthName = function() { return ['January', 'Februar
y', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'D
ecember'][this.getMonth()]; }
These two methods are pretty simple to use. If you want the month name just do
var d = new Date(); month = d.getMonthName();
If you want the name of the day, do
var d = new Date(); day = d.getDayName();
If you'd like the three character day name (mon/tue/wed, etc) then pass an argument
to getDayName. As long as the argument isn't false, null or any other falsey value the
name will be shortened to its three letter equivalent.
var d = new Date(); day = d.getDayName(true);
NEXT: Working With Dates
< JavaScript Functions
Exercise 1: String functions in JavaScript
JavaScript has some very interesting internal string manipulation functions.
1. charAt(x): Returns the character at the x position within the string.
var myString = 'jQuery FTW!!!';
alert(myString.charAt(7)); //output: F
2. charCodeAt(x) Returns the Unicode value of the character at position x within
the string.
var message="jquery4u";
alert(message.charAt(1)); //alerts "q"
3. concat(v1, v2,) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
var message="Sam";
var final=message.concat(" is a"," hopeless romantic.");
alert(final); //alerts "Sam is a hopeless romantic."
4. fromCharCode(c1, c2,) Returns a string created by using the specified
sequence of Unicode values (arguments c1, c2 etc). Method of String object, not
String instance. For example: String.fromCharCode().
alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyz
alert(String.fromCharCode(72,69,76,76,79)); //output: HELLO
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. Start is
an optional argument specifying the position within string to begin the search. Default
is 0.
//indexOf(char/substring)
var sentence="Hi, my name is Sam!";
if (sentence.indexOf("Sam")!=-1) {
alert("Sam is in there!");
}
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of
the searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. Start is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
var myString = 'javascript rox';
alert(myString.lastIndexOf('r'));
//output: 11
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found.
//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;
var myNumber = '999';
var myInt = myNumber.match(intRegex);
alert(isInt);
//output: 999
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
alert(isInt); //output: null
8. replace(regexp/substr, replacetext) Searches and replaces the regular
expression (or sub string) portion (match) with the replaced text instead.
//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or
-1 if not found.
//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';
var isInt = myNumber.search(intRegex);
alert(isInt);
//output: 0

var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
alert(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the start and
end index arguments, NOT including the end index itself. End is optional, and if
none is specified, the slice includes all characters from start to end of string.
//slice(start, end)
var text="excellent";
alert(text.slice(0,4)); //returns "exce"
alert(text.slice(2,4)); //returns "ce"
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional limit is an
integer that lets you specify the maximum number of elements to return.
//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at start
and through the specified number of characters, length. Length is optional, and if
omitted, up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"
13. substring(from, [to]) Returns the characters in a string between from and
to indexes, NOT including to inself. To is optional, and if omitted, up to the end
of the string is assumed.
//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
alert(myString);
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to
lowercase.
//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
alert(myString)
//output: javascript rox
15. toUpperCase() Returns the string with all of its characters converted to
uppercase.
//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
alert(myString)
//output: JAVASCRIPT ROX
Exercise 2: Creating JavaScript Functions
JavaScript also allows us to create custom functions to solve our everyday
functionalities. A custom function is a block of reusable code.
Let us create a function called hello which will just display an alert. Please note that in
the two examples below, you will not get any result because the functions were not
called and so will not be executed.
Example 1: creating the function
var hello = function () {
alert('i am saying hello');
};
Example 2:
function hello () {
alert('i am saying hello');
};
Example 3: executing the functions
var hello = function () {
alert('i am saying hello');
};
hello();
Example 4:
function hello () {
alert('i am saying hello');
};
hello();
The syntax of functions is shown below:
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
A function can have what we call arguments or parameters. Let us create a function
that will alert the first and last name of a person.
Example 5:
function myname(first,last) {
alert('Your full name is '+first+' '+last);
}
myname('Tony', 'Olawale');
Example 6: A function can also return a result
function myname(first,last) {
var r='Your full name is '+first+' '+last;
return r;
}
var fullname=myname('Tony', 'Olawale');
alert(fullname);
Exercise 3: Working With Arrays
An Array is an enumerated list of variables. It's a programming construct that allows
programmers to replace this
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
with this
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing
for easy looping through the data structure.
var x=[];
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
for(i=0; i<6; i++) {document.writeln(x[i]+'<br>');}
Which will output the following
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want
to create a new Array simply use brackets [] like this
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will
automatically increase the size of the Array as needed, as you add items into the
Array. Creating an Array with brackets instead of with thenew constructor avoids a bit
of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elemen
ts. var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add
more than one item then badArray would be initialized correctly since Javascript would
then be smart enough to know that you were initializing the array instead of stating
how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of
unintended results by using the new constructor, it's recommended you not use new
Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data
var myArray = ['January', 'February', 'March']; document.writeln('0>'+myArray[0]+'
<BR>'); // Will output: 0>January document.writeln('1>'+myArray[1]+'
<BR>'); // Will output: 1>February document.writeln('2>'+myArray[2]+
'<BR>'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[2] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>undefined document.writeln('3>'+myArray[3]+'<BR>'); // Will output:
3>undefined document.writeln('4>'+myArray[4]+'<BR>'); // Will outpu
t: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will out
put: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings,
functions, objects, other Arrays, even regular expressions
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]
; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 docu
ment.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! docum
ent.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.wr
iteln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.write
ln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln(
'4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension
arrays.
var x=[0,1,2,3,4,5]; var y=[x];
In the above example we created an array named x and assigned it as the first
element in the array y. If we ask for the value of y[0] it will return the contents of x as
a string because we didn't specify an index.
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance

document.writeln(bigArray[5][8][12][1])
would indicate bigArray's 5th index held an array, who's 8th index held an array,
who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; document.writeln(myArray
[1]); // Will output: one function passedByReference(refArray) { refArray[1] = '
changed'; } passedByReference(myArray); document.writeln(myArray[1]); // Wi
ll output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For
instance
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray;
newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray.slic
e(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: on
e function passedByReference(refArray) { refArray[1] = 'changed'; } passedB
yReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the
array. Since Arrays always start at zero, the length property is convenient for loops
since it will always be one greater than the actual index. For instance if the Array has
10 elements then the indexes will be 0-9, so as long as our counter is less than the
Array.length we'll cover the entire Array
for (var i=0; i<myArray.length; i++) {}
Going back to our undefined example above. Even though 3 of the Array items
are undefined the length property will still count them because it's always one higher
than the highest accessable index value.
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>Janua
ry document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February d
ocument.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined docu
ment.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined docume
nt.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined document.
writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March document.writeln(
'Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100
elements in an array and set the length to 50, Javascript will truncate the last 50
elements from the array (effectively deleting them). If you have 10 elements in an
array and set Array.length to 100 then the length of the array will be expanded to
100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = []; normalArray[1] = 'This is an enumerated array'; ale
rt(normalArray[1]); // outputs: This is an enumerated array var associativeArray
= []; associativeArray['person'] = 'John Smith'; alert(associativeArray
['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However All
arrays in Javascript are objects and Javascript's object syntax gives a basic emulation
of an associative Array. For this reason the example code above will actually work. Be
warned that this is not a real array and it has real pitfals if you try to use it. The
'person' element in the example becomes part of the Array object's properties and
methods, just like .length, .sort(), .splice(), and all the other built-in properties and
methods.
You can loop through an object's properties with the following loop
var associativeArray = []; associativeArray["one"] = "First"; associativeArray["two"
] = "Second"; associativeArray["three"] = "Third"; for (i in associativeArray) { d
ocument.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second,
three:Third };
In the above example, associativeArray.length will be zero because we didn't actually
put anything into the Array, we put it into associativeArray's
object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and
prototypes which have been added to the array and not just your data. A lot of
problems people have with the Prototype library is that their associative arrays break
because Prototype adds a few useful Prototype functions to the Array object and for i
in x loops pick up those additional methods. That's the pitfal of using Array/objects as
a poor man's associative array.
As a final example, the previous code will work regardless of whether you define
associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""),
or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are --
object properties, not Arrays.

Exercise 4: Working With Dates
Of all the core Javascript objects, I find Dates to be the most fascinating. Once you
learn a few small tricks everything about Javascript Dates just seem to fall into place
and you find that there's really nothing at all that you can't do with them, quickly, and
easily.
This reference will cover the Javascript Date Object, how it stores Dates, how you can
manipulate them, create calendars, countdown timers, prototype them to add your
own functionality, as well as provide a complete method reference.
Julian Dates
Julian Dates are a method of referencing time and dates based on how much time has
passed since an arbitrary number in the past. For instance, 215 days have presently
passed this year. If we know that January 1 begins on a Wednesday , then we know
that day 2 represents a Thursday in January. If we know there are 31 days in January
then we know that day 32 represents the first of February and we can figure out that
February 1st fell on a Saturday.
Javascript (and most languages) handle dates exactly as described above, only in
much grander fashion. Theepoch or starting point of Javascript's date system isn't
January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it
doesn't count just days! No Javascript counts the number of milliseconds that have
passed since January 1, 1970 and presently that number is 1,407,152,039,648.
Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers
indicate dates after 1970 and negative numbers indicate dates prior to 1970. For
instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript
counts in milliseconds and there are 1000 milliseconds in a single second so -1000
represents 1 second.
By a great coincidence Unix also uses January 1, 1970 as it's epoch date which means
a timestamp in Javascript will match a timestamp on your server as long as you take
some care with the timezones!
It will be quite a while before humanity has to worry about running out of dates!
Javascript can readily handle around 285,616 years on either side of the 1970 epoch.
Creating A New Date (Parsed)
To create a new Date all you have to do is to ask for one!
var myFirstDate = new Date();
This will create a new date object and since we did not specify a specific date or time,
the date will be equal to the instant it was created.
The Javascript Date Object has a very powerful date parser. While there are several
ways to create and set Dates. The one you're most likely to use is simply to specify
the date itself, as a string, when creating a new date.
var myDate = new Date('January 16, 1988');
Since we didn't specify a time the Date which is created will be for midnight in the
browser's timezone on January 16, 1988.
var myDate = new Date('January 16, 1988 2:54:16 pm');
Here we specify a specific time (note that there's a space between the time and pm).
Since we didn't specify a timezone the browser will use the user's timezone. We could
also have used millitary time (14:54:16).
Here we'll actually specify a time zone GMT in this case and below we'll print it out.
var myDate = new Date('January 16, 1988 2:54:16 pm GMT');
Sat Jan 16 1988 15:54:16 GMT+0100 (W. Central Africa Standard Time)
Unless you actually live in the Greenwich Mean Timezone, the date requested and the
date printed are unlikely to match. The created date is actually 2:54:16 in the GMT
timezone, however when we printed the date out, since we didn't specify anything
special, the date was printed in the Browser's time zone so the browser did a little
conversion for us to ensure the time we printed was the ACTUAL time relative to the
browser.
That's a little confusing so let's try for something different. Every New Years Eve, the
city of New York holds a big celebration and the ball is dropped at precisely midnight
in the eastern timezone. So lets create a date for that event.
var myDate = new Date('January 1, 2000 EST');
Since we didn't specify a time, Javascript will assume midnight for us, we did specify a
time zone so the actual time will be midnight in the eastern time zone.
Now when we print the date out we'll get that little timezone conversion and you can
see what time the ball will be dropping in your timezone! (of course people in the
eastern timezone will see the correct time).
Sat Jan 01 2000 06:00:00 GMT+0100 (W. Central Africa Standard Time)
Creating A New Date (arguments)
You can also create a new date by passing the date values as arugments to the Date
object. The arguments are Year, Month, Date and optionally hours, minutes, seconds,
and milliseconds. The first argument, year, is special. If it's a string the Date object
will try to parse it (see previous section), if it's a long integer it will try to use it as a
julian number. If there are more than one argument it will build the date from your
supplied arguments.
var d1 = new Date('January 1, 1970'); // Date as a parse
var d2 = new Date(0); // Date as a julian number
var d3 = new Date(1970, 0, 1); // Date as arguments
Notice we use zero as the month when creating d3, that's because Javascript months
go from 0 to 11 where January is zero. This is a pretty big gotcha if you're not careful!
The argument list is as follows
dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);
Working With Julian Day Numbers
Working with Julian Dates requires division and modulus. Division will discard the
portion of the date you no longer need and modulus (which is the remainder of
division) will return the portion of the date you are looking for.
Most people don't need milliseconds when doing date calculation, so we just divide
the Julian Date Number by 1,000. So if we have a Julian Day Number of
1,177,303,066,354 then dividing this by 1,000 will give us a day number of
1,177,303,066 -- a number which no longer holds information about the milliseconds
in the date.
To get the number of seconds this represents, we take the modulus of 60 because
there are 60 seconds in a minute.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
Now that we have the number of seconds we discard the seconds from the Julian date
by dividing it by 60.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
So now our day number has been stripped of milliseconds and seconds. We can find
out how many minutes the number represents by taking the modulus of 60 since there
are 60 minutes in an hour.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
And we can discard the minutes from the original number by dividing it by 60. What
remains are hours and days. We can get the hours by taking the modulus of 24 since
there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,
leaving only the number of days.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
dayNumber = dayNumber/60; // dayNumber = 327,028
var hours = dayNumber % 24; // hours = 4
dayNumber = dayNumber/24 // dayNumber = 13,626
Or 13,624 days between January 1, 1970 and Mon Apr 23 2007 05:37:46 GMT+0100
(W. Central Africa Standard Time)
Countdown Timers In Javascript
In the previous section we broke a day number out into its component milliseconds,
seconds, minutes, hours, and days. The number we used was the number of
milliseconds that had elapsed since January 1, 1970. But we could just as easily have
used another date. Lets take the difference between now and the end of the year.
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
This code creates two julian dates, now and newYear. By
subtracting now from newYear we get an integer which represents the difference
between the two dates, specifically: 12,914,813,502.
We can use division and modulus to extract the time from this number just like we did
in the previous section only now we're computing the difference between now and the
new year instead of a date and January 1, 1970.
This article is generating now and newYear in real-time so the values below are the
actual values until the new year!
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
This gives us a value of 149 Days, 11 hours, 26 minutes, 53 seconds, until Thu Jan 01
2015 00:00:00 GMT+0100 (W. Central Africa Standard Time).
Making a Timer
In the example above now is equal to the instant it is created while newYear is a
constant value, always equal to January 1 of next year. So it's actually very easy to
make a timer. All we have to do is turn the code above into a function, set up a
setTimeout command, and create a html division somewhere on the page to hold our
timer. Here's the new code!


<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyNewYear() {
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);

// We'll build a display string instead of doing document.writeln
var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
outStr+= ' minutes, ' + seconds + ' seconds until the new year!';
// Insert our display string into the countdown span.
document.getElementById('countdown').innerHTML=outStr;
// call this function again in exactly 1 second.
setTimeout("happyNewYear()",1000);
}
// call the countdown function (will start the timer)
happyNewYear();
</script>
When the function is called (every second), now is always set to the current, ever
advancing date, while the newYear always remains a constant. So the function works
to countdown the passing time to the destination date (new year).
And here's the result!
Does the time appear a bit off? Maybe because right now you're in Daylight time and
the new year is in daylight savings time! If this is the case, once everyone falls back
the timer will again be in sync with your expectations!
Making A Clock
Making a clock is very similar to making a countdown timer. All we have to do is to
create a new date and get it's hours, minutes, and seconds.
<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>
<script type="text/javascript">
function clock() {
var now = new Date();
var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
document.getElementById('clockDiv').innerHTML=outStr;
setTimeout('clock()',1000);
}
clock();
</script>
And the result (in military time):
Getting The Number Of Days In A Month
Javascript has a little quirk where a date of zero will set the date to be the last day of
the previous month. Likewise is there are 30 days in a month and you set a date of 31
it will be the 1st day of the next month, a date of 40 would be the 10th day of the
next month. This can lead to some very weird funkiness if you're not careful but we
can definitely exploit this for a useful prototype which will give us the number of days
in a specific month. We'll do this up as a prototype so it's available to all our Dates.
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
var d = new Date();
document.writeln('Number of days in this month: '+d.daysInMonth());
And the result (live!):
Getting The Name Of The Day And Month
While the Javascript Date Object has many useful features, one glaring oversight is
that when you ask it for the day or month it will return only the numerical
representation. This is easy enough to fix with prototypes however.
Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Mon
day', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; if (shortName) {
return Days[this.getDay()].substr(0,3); } else { return Days[this.getDay()];
} } Date.prototype.getMonthName = function() { return ['January', 'Februar
y', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'D
ecember'][this.getMonth()]; }
These two methods are pretty simple to use. If you want the month name just do
var d = new Date(); month = d.getMonthName();
If you want the name of the day, do
var d = new Date(); day = d.getDayName();
If you'd like the three character day name (mon/tue/wed, etc) then pass an argument
to getDayName. As long as the argument isn't false, null or any other falsey value the
name will be shortened to its three letter equivalent.
var d = new Date(); day = d.getDayName(true);
< Working With Arrays

Welcome To JavaScript
Introduction to JavaScript
Writing Javascript Code
Writing Javascript Code :: Coding Conventions
Write Javascript: the Script Element
Javascript & DOM
Exercise 1: Introduction to Javascript
Javascript has lots of uses, it is not only used to develop websites. This Javascript
Editor that was introduced in this tutorial is a windows
software, but javascript code was used in 95% of its development.
Javascript can also be used to develop games (you can check this link as an
example http://msdn.microsoft.com/en-us/library/windows/apps/hh465158.aspx).
Basic Facts:
Javascript is said to be the most popular language according to some sources. It is
also said by some to be the world's most misunderstood programming language.
I am however interested in technicalities since this is a practical section.
Here are some key facts about JavaScript:
1. Javascript has very little in common with Java, so being a Java guru does not
necessarily mean you will understand javascript (i use both languages so i know
this to be a fact).
2. JavaScript is an object oriented dynamic language: it has types and operators,
core objects, and methods. Its syntax comes from the Java and C languages, so
many structures from those languages apply to JavaScript as well.
3. JavaScript does not have classes; instead, the class functionality is accomplished
by object prototypes.
4. Javascript functions are objects, giving functions the capacity to hold executable
code and be passed around like any other object.
5. Javascript has lots of uses, it is not only used to develop websites. This Javascript
Editor that was introduced in this tutorial is a windows software, but javascript
code was used in 95% of its development.
6. Javascript is exclusively a client-sided language, this means that it must first be
downloaded from a server and then executed inside the browser. Unlike server-
sided scripts like PHP,PERL,JSP which are executed on the browser and the output
if any is sent to the client.
Exercise 2: Writing Javascript Code
Javascript code is written as plain text, with a plain text editor
A simple javascript code is:
alert('Welcome to Javascript');
You can embed this code into a web page
various ways:
1. You can embed it into an html page directly
<html>
<head>
<title>Javascript Example</title>
<script>
alert('Welcome to Javascript');
</script>
</head>
<body>
My web page
</body>
</html>
2. You can embed it into an html page directly
<script>
alert('Welcome to Javascript');
</script>
3. You can put it inside an external file and link it to an html page indirectly
example.js
alert('Welcome to Javascript');
sample.html
<html>
<head>
<title>Javascript Example</title>
<script src='example.js'></script>
</head>
<body>
My web page
</body>
</html>
Exercise 3: Writing Javascript Code :: Coding Conventions
I am going to reference http://msdn.microsoft.com/en-us/library/ie/cte3c772
In this subsection, we are going to be looking at javascript as a programming
language. Most of the terminologies here will be explained as we delve more into the
language.
Like many other programming languages, JavaScript is organized into statements,
blocks consisting of related sets of statements, and comments. Within a statement
you can use variables, strings, numbers, and expressions.
A JavaScript program is a collection of statements. JavaScript statements
combine expressions in such a way that they carry out one complete task.
How to write statements in javascript
A statement consists of one or more expressions, keywords, or operators (symbols).
Typically, a statement is written on a single line, although a statement can be written
over two or more lines.
Also, two or more statements can be written on the same line by separating them
with semicolons. In general, each new line begins a
new statement. It is a good idea to terminate your statements explicitly. You do this
with the semicolon ( ; ), which is the JavaScript statement
termination character.
Here are two examples of JavaScript statements.
The sentences after the // characters are
comments, which are explanatory remarks in the
program.
var aBird = 'Robin'; // Assign the text "Robin" to the variable aBird.
var today = new Date(); // Assign today's date to the variable today.
A group of JavaScript statements surrounded by braces ({}) is called a
block.
Statements grouped into a block can generally be treated as a single statement. This
means you can use blocks in most places that JavaScript expects a single statement.
Notable exceptions include the headers of for and while loops. Notice that the single
statements within a block end in
semicolons, but the block itself does not.
An example script:
function inchestometers(inches)
{
if (inches < 0)
return -1;
else
{
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write('the value in meters is ' + meters);
This script is showing a combination of javascript statements. You can copy and paste
this code into the Javascript Editor to see the output.
You do not need to understand these codes yet, we are only introducing how the
codes are written.
Exercise 4: Write Javascript: the Script Element
When you want to use JavaScript on a website it has to be included within a SCRIPT
element:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JavaScript!</title>
</head>
<body>
<script type="text/javascript">
// <![CDATA[
// ]]>
</script>
</body>
</html>
The TYPE attribute should be set to 'text/javascript' or no TYPE attribute at all.
Linking to External Scripts
If you want to link to an external script file then simply add an SRC attribute to your
SCRIPT element corresponding to its location. It's normally a better idea to have
seperate script files than to write code inline as it means the browser can cache the
file. Plus you don't need to worry about any of that CDATA nonsense:
<script type="text/javascript" src="my-script.js"></script>
Exercise 5: Javascript & DOM
I think it will be good to introduce DOM at this point for reference sake, if you do not
understand all these, dont stress yourself, as the class goes on, we will make
references back to this and it will all make sense.
The Document Object Model, normally abbreviated to DOM, is the API (application
interface) through which JavaScript interacts with content within a website. JavaScript
and the DOM are usually seen as a single entity since JavaScript is most commonly
used for this purpose (interacting with content on the web). The DOM API is used to
access, traverse and manipulate HTML and XML documents.
The window object serves as the global object, you access it by just typing "window".
It's within this object that all of your JavaScript code is executed. Like all objects it
has properties and methods.
=> A property is a variable stored under an object. All variables created on a web-
page authomatically become properties of the window object.
=> A method is a function stored under an object. Since all functions are stored under
(at least) the window object they can all be referred to as 'methods'.
The DOM creates a hierarcy corresponding to the structure of each web document.
This hierarchy is made up of nodes. There are several different types of DOM nodes,
the most important are 'Element', 'Text' and 'Document'.
=> An 'Element' node represents an element within a page. So if you have a
paragraph element ('<p>') then it can be accessed through the DOM as a node.
=> A 'Text' node represents all text (within elements) within a page. So if your
paragraph has a bit of text in it can be directly accessed through the DOM.
=> The 'Document' node represents the entire document. (it's the root-node of the
DOM hierarchy/tree).
=> Also note that element attributes are DOM nodes themselves.
Most importantly: Each layout engine has a slightly different
implementation of the DOM standard. For example, the Firefox web
browser, which uses the Gecko layout engine, has quite a good
implementation (although, not entirely inline with the W3C specification)
but Internet Explorer, which uses the Trident layout engine is known for it's
buggy and incomplete implementation; a cause of much anguish within the
web development community!
And this explains why javascript behaves differently in different browsers,
this is the reason why libraries like jQuery are created to solve this problem
and to make javascript easier to use.
The images below show two different outlines of the typical DOM hierarchy
(Simplified)
DOM ILLUSTRATION 1: Flow Chart
DOM ILLUSTRATION 2: Tree View
NEXT: JavaScript Alert Box & Math Rules
< back to basics course outline
JavaScript Alert Box & Math Rules
Display messages with alert
Math Rules: Order of operation math rules
The Javascript Maths Object
Exercise 1: Display messages with alert
An alert box is often used if you want to make sure information comes through to the
user. When an alert box pops up, the user will have to click "OK" to proceed.
Syntax: alert('message');
alternative syntaxes:
alert('message')
window.alert('message') // reference to current window
self.alert('message') // reference to current window
top.alert('message') // top-level frameset
parent.alert('message') // parent frame in a frameset
Examples:
alert('I am an alert box!');
Exercise 2: Math Rules: Order of operation math rules
The simplest way I can explain how javascript handles mathematics is by
using the popular bodmas rules.
B -Brackets first
O - Orders (ie Powers and Square Roots, etc.)
DM - Division and Multiplication (left-to-right)
AS - Addition and Subtraction (left-to-right)
Using bodmas rules in javascript:
Example 1:
document.write(6 * (5 + 3)); //answer 48
Example 2:
document.write(2 + 5 * 3); //answer 17
Example 3:
document.write(30/5 * 3); //answer 18
Please note that the arithmetic sign for multiplication is (*) rather than (x).
Advanced learners: Javascript uses what we call the Operator Precedence, this means
that operators higher takes precedence (just like bodmas).
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
Exercise 3: The Javascript Maths Object
Math is a built-in object that has properties and methods for mathematical constants
and functions. Not a function object.
You can use it to perform other tasks such as get the value of PI (as in length of a
cycle 2*PI*R).
Example 1: Calculate the perimeter of a cycle with radius 16.
document.write(2 * Math.PI * 16); //answer 100.53096491487338
Example 2: Calculate the square root of 64
document.write(Math.sqrt(64)); //answer 8
Example 3: Calculate the sine of 90
document.write(Math.sin(90));
Example 4: Calculate the cosine of 90
document.write(Math.cos(90));
You can read more about the maths object here - https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Math
NEXT: Working With Variables, Strings & Prompt Dialog
< Welcome to JavaScript
Working With Variables, Strings & Prompt
Dialog
Variables: Store data with variables
Prompt Box: Ask questions with prompt
Adding Strings: Joining strings and numbers with +
Exercise 1: Store Data With Variables
I am going to use some w3school tutorials to illustrate variables to an extent.
JavaScript variables are "containers" for storing information.
You can test this out in the javascript editor.
var x = 5;
var y = 6;
var z = x + y;
alert(x);
alert(y);
alert(z);
You will get an alert with 5,6 and 11.
JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x = 5) or
expressions (z = x + y).
* Variable can have short names (like x and y) or more descriptive names (age, sum,
totalVolume).
* Variable names can contain letters, digits, underscores, and dollar signs.
* Variable names must begin with a letter
* Variable names can also begin with $ and _ (but we will not use it)
* Variable names are case sensitive (y and Y are different variables)
* Reserved words (like JavaScript keywords) cannot be used as variable names.
Javascript reserve keywords:
abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default,delete,do,double,else,enum
export,extends,false,final,finally,float,for,function,goto,if,implements,import,in,instanceof,int,interface,long,native,new,null,package,private,protected,
public,return,short,static,super,switch,synchronized,this,throw,throws,transient,true,try,typeof,var,void,volatile,while,with
Exercise 2: Prompt Box: Ask questions with prompt
The Window.prompt() displays a dialog with an optional message
prompting the user to input some text.
Syntax: result = window.prompt(text, value);
* result is a string containing the text entered by the user, or the value null.
* text is a string of text to display to the user. This parameter is optional and can be
omitted if there is nothing to show in the prompt window.
* value is a string containing the default value displayed in the text input field. It is
an optional parameter. Note that in Internet Explorer 7 and 8, if you do not provide
this parameter, the string "undefined" is the default value
Example 1:
var sign = prompt('What is your sign?');
Example 2: enter scorpio as sign and see the resulting alert. If statement block shall
be treated in a later chapter.
var sign = prompt('What is your sign?');
if (sign == 'scorpio') {
alert('Wow! I am a Scorpio too!');
}
Exercise 3: Adding Strings: Joining strings and numbers with
+
Javascript handles strings and numbers in a different way that other languages.
Example 1: Let us join 2 strings together
var first='Tony';
var last='Ogundipe';
var result=first+last;
document.write(result); //result will be TonyOgundipe
Example 2: Let us join a string (tony) with a number (2014)
var name='Tony';
var year=2014;
var result=name+year;
document.write(result); //result will be Tony2014
NEXT: If Statements, Boolean values & Null values
< JavaScript Alert Box & Math Rules
If Statements, Boolean values & Null values
Check user responses with if statements
Boolean values: true & false
Null value: The special value null
Exercise 1: Check user responses with if statements
One of the most important features of a computer language is the capability to test
and compare values. This allows your scripts to behave differently based on the
values of variables, or based on input from the user.
The if statement is the main conditional statement in JavaScript. This statement
means much the same in JavaScript as it does in Englishfor example, here is a
typical conditional statement in English:
If the phone rings, answer it.
This statement consists of two parts: a condition (If the phone rings) and an action
(answer it). The if statement in JavaScript works much the same way. Here is an
example of a basic if statement:
Example 1: this will not yield any result since the condition is not yet meth
if (a == 1) window.alert('Found a 1!');
This statement includes a condition (if a equals 1) and an action (display a message).
This statement checks the variable a and, if it has a value of 1, displays an alert
message. Otherwise, it does nothing.
If you use an if statement like the preceding example, you can use a single statement
as the action. You can also use multiple statements for the action by enclosing them
in braces ({}), as shown here:
Example 2: this will yield result because the condition was met initially.
var a=1;
if (a == 1) {
window.alert('Found a 1!');
a = 0;
}
This block of statements checks the variable a once again. If it finds a value of 1, it
displays a message and sets a back to 0.
Conditional Operators
While the action part of an if statement can include any of the JavaScript statements
you've already learned (and any others, for that matter), the condition part of the
statement uses its own syntax. This is called a conditional expression.
A conditional expression includes two values to be compared (in the preceding
example, the values were a and 1). These values can be variables, constants, or even
expressions in themselves.
Note:
Either side of the conditional expression can be a variable, a constant, or an
expression. You can compare a variable and a value, or compare two variables. (You
can compare two constants, but there's usually no reason to.)
Between the two values to be compared is a conditional operator. This operator tells
JavaScript how to compare the two values. For instance, the == operator is used to
test whether the two values are equal. A variety of conditional operators are
available:
Using Comparison Operators / Conditional Operators In Javascript
== (is equal to)
!= (is not equal to)
=== (equal value and equal type)
!== (not equal value or not equal type)
< (is less than)
> (is greater than)
>= (is greater than or equal to)
<= (is less than or equal to)
Example 3a: Note that x is an integer here
var x = 5;
if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 3b: Note that x is a string here
var x = '5';
if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}
Both will give the same result, however, using === which compares both values and
variable types, a different result will be seen
Example 4a: Note that x is an integer here
var x = 5;
if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 4b: Note that x is a string here
var x = '5';
if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}
Example 5: using comparison
var x=5,y=8;
if(x>y) {alert('x is greater than y');} else {alert('y is greater than x');}
Note:
Be sure not to confuse the equality operator (==) with the assignment operator (=),
even though they both might be read as "equals." Remember to use = when assigning
a value to a variable, and == when comparing values. Confusing these two is one of
the most common mistakes in JavaScript programming.
Exercise 2: Boolean values: true & false
Boolean logic is something used in most programming languages, including JavaScript.
It's very useful to know at least a little bit about it. In JavaScript, you mostly need it in
if() statements.
In Boolean logic, a statement can have two values, true or false. When using Boolean
logic in philosophy, the statement can be a sentence, like
It rains today.
In more down-to-earth applications like JavaScript, a statement is something like
x == 4
Both statements can be either true or false. When writing a program it is often
necessary to see if a statement is true or false. Usually this is done by an if()
statement. If the statement x == 4 is true, then do something:
if (x==4) {
do something
}
All this is not surprising. Boolean logic, however, also offers possibilities to evaluate a
whole string of statements and see whether the whole string is true or false. Like:
It rains today AND my feet are getting wet
In Boolean logic, this longer statement is true if it rains today is true AND my feet are
getting wet is true.
It rains today OR my feet are getting wet
In Boolean logic, this statement is true if it rains today is true OR if your feet are
getting wet is true OR if both statements are true.
This is also very useful when writing programs. For instance, suppose you want to do
something if x==4 OR y==1. Then you write:
if (x==4 || y==1) {
do something
}
The statement (x==4 || y==1) is true when x is 4 OR y is 1.
Exercise 3: Null value: The special value null
Javascript handles strings and numbers in a different way that other languages.
Example 1: Let us join 2 strings together
var first='Tony';
var last='Ogundipe';
var result=first+last;
document.write(result); //result will be TonyOgundipe
Example 2: Let us join a string (tony) with a number (2014)
var name='Tony';
var year=2014;
var result=name+year;
document.write(result); //result will be Tony2014
NEXT: Confirm Command, Combining conditions & While loop
< Working With Variables, Strings & Prompt Dialog
Confirm Command, Combining conditions &
While loop
The confirm command
Combining conditions with && and ||
While loop: Repeat code with while loops
Exercise 1: The confirm command
This is used to confirm a user about certain action, and decide between two choices
depending on what the user chooses.
Syntax: window.confirm()
Note that the value x is a boolean value, the value will be TRUE if okay is clicked, and
FALSE when cancel is clicked.
Example:
var x=window.confirm('Are you sure you are ok?');
if (x)
window.alert('Good!');
else
window.alert('Too bad');
It can also be rewritten like this:
var x=window.confirm('Are you sure you are ok?');
if (x) {window.alert('Good!');}
else {window.alert('Too bad');}
or
var x=window.confirm('Are you sure you are ok?');
if (x==true) {window.alert('Good!');}
else {window.alert('Too bad');}
Exercise 2: Combining conditions with && and ||
We have looked at the comparison operators above (>,<,==,=== etc), now, we
want to learn how to write more extended if statements using logical operators.
The Logical Operators are:
&& (and)
|| (or)
! (not)
Example 1: if either condition is true, the entire statement returns true
if ((20 > 500) || (50 < 200)) {
alert('20 is not greater than 500 but 50 is definitely less than 200');
}
Example 2: if both conditions are true, then the entire statement returns true
if ((20 > 500) && (50 < 200)) {
alert('Both conditions are not true, so this block will not execute');
}
Example 3: using not. Not causes reversal of conditions, i.e changes true to false and
false to true.
if ((20 != 500) && (50 != 200)) {
alert('20 is not 500 and 50 is not 200, so both statements are correct');
}
Example 4: this will not give any result
if ((20 != 20) && (50 != 200)) {
alert('this block will not run because 20 is 20 and cannot be anything else');
}
Javascript Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable
based on some condition.
Syntax: variablename = (condition) ? value1:value2
Consider this statement:
var age=15;
if(age<18) {var voteable='Too young';} else {var voteable='Old enough';}
alert(voteable);
it can be rewritten using the conditional operator as shown below with exactly the
same result:
var age=15;
var voteable = (age < 18) ? 'Too young':'Old enough';
alert(voteable);
Exercise 3: While loop: Repeat code with while loops
Loops can execute a block of code as long as a specified condition is true.
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
code block to be executed
}
Example: this will iterate the value of i from 1 to 5.
var i=1;
while (i <= 5) {
alert(i);
i++;
}
There are more complicated ways of using while, but this will suffice for now and so
we end this tutorial.
NEXT: JavaScript Functions, Arrays & Dates
< If Statements, Boolean values & Null values
JavaScript Functions, Arrays & Dates
String functions in JavaScript
JavaScript Functions
Working With Arrays
Working With Dates
Exercise 1: String functions in JavaScript
JavaScript has some very interesting internal string manipulation functions.
1. charAt(x): Returns the character at the x position within the string.
var myString = 'jQuery FTW!!!';
alert(myString.charAt(7)); //output: F
2. charCodeAt(x) Returns the Unicode value of the character at position x within
the string.
var message="jquery4u";
alert(message.charAt(1)); //alerts "q"
3. concat(v1, v2,) Combines one or more strings (arguments v1, v2 etc) into the
existing one and returns the combined string. Original string is not modified.
var message="Sam";
var final=message.concat(" is a"," hopeless romantic.");
alert(final); //alerts "Sam is a hopeless romantic."
4. fromCharCode(c1, c2,) Returns a string created by using the specified
sequence of Unicode values (arguments c1, c2 etc). Method of String object, not
String instance. For example: String.fromCharCode().
alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyz
alert(String.fromCharCode(72,69,76,76,79)); //output: HELLO
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. Start is
an optional argument specifying the position within string to begin the search. Default
is 0.
//indexOf(char/substring)
var sentence="Hi, my name is Sam!";
if (sentence.indexOf("Sam")!=-1) {
alert("Sam is in there!");
}
6. lastIndexOf(substr, [start]) Searches and (if found) returns the index number of
the searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. Start is an optional argument specifying the
position within string to begin the search. Default is string.length-1.
//lastIndexOf(substr, [start])
var myString = 'javascript rox';
alert(myString.lastIndexOf('r'));
//output: 11
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found.
//match(regexp) //select integers only
var intRegex = /[0-9 -()+]+$/;
var myNumber = '999';
var myInt = myNumber.match(intRegex);
alert(isInt);
//output: 999
var myString = '999 JS Coders';
var myInt = myString.match(intRegex);
alert(isInt); //output: null
8. replace(regexp/substr, replacetext) Searches and replaces the regular
expression (or sub string) portion (match) with the replaced text instead.
//replace(substr, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(/JavaScript/i, "jQuery"));
//output: 999 jQuery Coders

//replace(regexp, replacetext)
var myString = '999 JavaScript Coders';
alert(myString.replace(new RegExp( "999", "gi" ), "The"));
//output: The JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or
-1 if not found.
//search(regexp)
var intRegex = /[0-9 -()+]+$/;

var myNumber = '999';
var isInt = myNumber.search(intRegex);
alert(isInt);
//output: 0

var myString = '999 JS Coders';
var isInt = myString.search(intRegex);
alert(isInt);
//output: -1
10. slice(start, [end]) Returns a substring of the string based on the start and
end index arguments, NOT including the end index itself. End is optional, and if
none is specified, the slice includes all characters from start to end of string.
//slice(start, end)
var text="excellent";
alert(text.slice(0,4)); //returns "exce"
alert(text.slice(2,4)); //returns "ce"
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional limit is an
integer that lets you specify the maximum number of elements to return.
//split(delimiter)
var message="Welcome to jQuery4u"
//word[0] contains "We"
//word[1] contains "lcome to jQuery4u"
var word=message.split("l")
12. substr(start, [length]) Returns the characters in a string beginning at start
and through the specified number of characters, length. Length is optional, and if
omitted, up to the end of the string is assumed.
//substring(from, to)
var text="excellent"
text.substring(0,4) //returns "exce"
text.substring(2,4) //returns "ce"
13. substring(from, [to]) Returns the characters in a string between from and
to indexes, NOT including to inself. To is optional, and if omitted, up to the end
of the string is assumed.
//substring(from, [to])
var myString = 'javascript rox';
myString = myString.substring(0,10);
alert(myString);
//output: javascript
14. toLowerCase() Returns the string with all of its characters converted to
lowercase.
//toLowerCase()
var myString = 'JAVASCRIPT ROX';
myString = myString.toLowerCase();
alert(myString)
//output: javascript rox
15. toUpperCase() Returns the string with all of its characters converted to
uppercase.
//toUpperCase()
var myString = 'javascript rox';
myString = myString.toUpperCase();
alert(myString)
//output: JAVASCRIPT ROX
Exercise 2: Creating JavaScript Functions
JavaScript also allows us to create custom functions to solve our everyday
functionalities. A custom function is a block of reusable code.
Let us create a function called hello which will just display an alert. Please note that in
the two examples below, you will not get any result because the functions were not
called and so will not be executed.
Example 1: creating the function
var hello = function () {
alert('i am saying hello');
};
Example 2:
function hello () {
alert('i am saying hello');
};
Example 3: executing the functions
var hello = function () {
alert('i am saying hello');
};
hello();
Example 4:
function hello () {
alert('i am saying hello');
};
hello();
The syntax of functions is shown below:
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
A function can have what we call arguments or parameters. Let us create a function
that will alert the first and last name of a person.
Example 5:
function myname(first,last) {
alert('Your full name is '+first+' '+last);
}
myname('Tony', 'Olawale');
Example 6: A function can also return a result
function myname(first,last) {
var r='Your full name is '+first+' '+last;
return r;
}
var fullname=myname('Tony', 'Olawale');
alert(fullname);
Exercise 3: Working With Arrays
An Array is an enumerated list of variables. It's a programming construct that allows
programmers to replace this
x0=0; x1=1; x2=2; x3=3; x4=4; x5=5;
with this
x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5;
The index (the number in the brackets [] )can be referenced by a variable, allowing
for easy looping through the data structure.
var x=[];
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
for(i=0; i<6; i++) {document.writeln(x[i]+'<br>');}
Which will output the following
0
1
2
3
4
5
Creating A New Array
Most tutorials start out introducing you to arrays as such
var myArray = new Array(10);
Current best-practice eschews the new keyword on Javascript primitives. If you want
to create a new Array simply use brackets [] like this
var myArray = [];
You don't need to tell Javascript how many items to size the Array for. Javascript will
automatically increase the size of the Array as needed, as you add items into the
Array. Creating an Array with brackets instead of with thenew constructor avoids a bit
of confusion where you want to initialize only one integer. For instance.
var badArray = new Array(10); // Creates an empty Array that's sized for 10 elemen
ts. var goodArray= [10]; // Creates an Array with 10 as the first element.
As you can see these two lines do two very different things. If you had wanted to add
more than one item then badArray would be initialized correctly since Javascript would
then be smart enough to know that you were initializing the array instead of stating
how many elements you wanted to add.
Since the new constructor is not necessary with Arrays and there's a slight chance of
unintended results by using the new constructor, it's recommended you not use new
Array() to create an Array.
Initializing An Array
You can initialize your array with pre-defined data
var myArray = ['January', 'February', 'March']; document.writeln('0>'+myArray[0]+'
<BR>'); // Will output: 0>January document.writeln('1>'+myArray[1]+'
<BR>'); // Will output: 1>February document.writeln('2>'+myArray[2]+
'<BR>'); // Will output: 2>March
You can inizialize your array with data after an empty array has been created
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[2] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>March
If you skip an element, the blank Array elements will be of type undefined
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>
January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>
February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2
>undefined document.writeln('3>'+myArray[3]+'<BR>'); // Will output:
3>undefined document.writeln('4>'+myArray[4]+'<BR>'); // Will outpu
t: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will out
put: 5>March
Storing Data In An Array
An array can store anything you can assign to a variable: booleans, numbers, strings,
functions, objects, other Arrays, even regular expressions
var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]
; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 docu
ment.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! docum
ent.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.wr
iteln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.write
ln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln(
'4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true
Multi-Dimensional Arrays
Since an Array can store other Arrays you can get the benefit of multi-dimension
arrays.
var x=[0,1,2,3,4,5]; var y=[x];
In the above example we created an array named x and assigned it as the first
element in the array y. If we ask for the value of y[0] it will return the contents of x as
a string because we didn't specify an index.
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0]); // Will output: 0,1,2,3,4,5
If we wanted the third index we'd access it this way
var x=[0,1,2,3,4,5]; var y=[x]; document.writeln(y[0][3]); // Will output: 2
There's no defined limit to how many Arrays you can nest in this manner. For instance

document.writeln(bigArray[5][8][12][1])
would indicate bigArray's 5th index held an array, who's 8th index held an array,
who's 12th index held an array, who's first index contains the data we want.
Javascript Arrays Are Passed By Reference
Arrays are passed to functions by reference, or as a pointer to the original. This means
anything you do to the Array inside the function affects the original.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; document.writeln(myArray
[1]); // Will output: one function passedByReference(refArray) { refArray[1] = '
changed'; } passedByReference(myArray); document.writeln(myArray[1]); // Wi
ll output: changed
Javascript Arrays Are Assigned By Reference
Assigning an Array to a new variable creates a pointer to the original Array. For
instance
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray;
newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed
Passing Arrays As Values
To pass an Array by value instead of by reference, use the Array.slice() method.
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray.slic
e(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: on
e function passedByReference(refArray) { refArray[1] = 'changed'; } passedB
yReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one
Array.length
Every Array has a length property. This always contains the number of elements in the
array. Since Arrays always start at zero, the length property is convenient for loops
since it will always be one greater than the actual index. For instance if the Array has
10 elements then the indexes will be 0-9, so as long as our counter is less than the
Array.length we'll cover the entire Array
for (var i=0; i<myArray.length; i++) {}
Going back to our undefined example above. Even though 3 of the Array items
are undefined the length property will still count them because it's always one higher
than the highest accessable index value.
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] =
'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>Janua
ry document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February d
ocument.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>undefined docu
ment.writeln('3>'+myArray[3]+'<BR>'); // Will output: 3>undefined docume
nt.writeln('4>'+myArray[4]+'<BR>'); // Will output: 4>undefined document.
writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March document.writeln(
'Array Length: '+myArray.length); // Will output: Array Length: 6
Array.length is NOT a read-only value, you can set it as you wish. If you have 100
elements in an array and set the length to 50, Javascript will truncate the last 50
elements from the array (effectively deleting them). If you have 10 elements in an
array and set Array.length to 100 then the length of the array will be expanded to
100, creating 90 undefined elements after the original 10 items.
Javascript Does Not Support Associative Arrays
An associative array is an array which uses a string instead of a number as an index.
var normalArray = []; normalArray[1] = 'This is an enumerated array'; ale
rt(normalArray[1]); // outputs: This is an enumerated array var associativeArray
= []; associativeArray['person'] = 'John Smith'; alert(associativeArray
['person']); // outputs: John Smith
Javascript does not have, and does not support Associative Arrays. However All
arrays in Javascript are objects and Javascript's object syntax gives a basic emulation
of an associative Array. For this reason the example code above will actually work. Be
warned that this is not a real array and it has real pitfals if you try to use it. The
'person' element in the example becomes part of the Array object's properties and
methods, just like .length, .sort(), .splice(), and all the other built-in properties and
methods.
You can loop through an object's properties with the following loop
var associativeArray = []; associativeArray["one"] = "First"; associativeArray["two"
] = "Second"; associativeArray["three"] = "Third"; for (i in associativeArray) { d
ocument.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second,
three:Third };
In the above example, associativeArray.length will be zero because we didn't actually
put anything into the Array, we put it into associativeArray's
object. associativeArray[0] will be undefined.
The loop in the above example will also pick up any methods, properties, and
prototypes which have been added to the array and not just your data. A lot of
problems people have with the Prototype library is that their associative arrays break
because Prototype adds a few useful Prototype functions to the Array object and for i
in x loops pick up those additional methods. That's the pitfal of using Array/objects as
a poor man's associative array.
As a final example, the previous code will work regardless of whether you define
associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(""),
or any other Javascript object.
The bottom line is -- don't try to use associative arrays, code for what they are --
object properties, not Arrays.

Exercise 4: Working With Dates
Of all the core Javascript objects, I find Dates to be the most fascinating. Once you
learn a few small tricks everything about Javascript Dates just seem to fall into place
and you find that there's really nothing at all that you can't do with them, quickly, and
easily.
This reference will cover the Javascript Date Object, how it stores Dates, how you can
manipulate them, create calendars, countdown timers, prototype them to add your
own functionality, as well as provide a complete method reference.
Julian Dates
Julian Dates are a method of referencing time and dates based on how much time has
passed since an arbitrary number in the past. For instance, 215 days have presently
passed this year. If we know that January 1 begins on a Wednesday , then we know
that day 2 represents a Thursday in January. If we know there are 31 days in January
then we know that day 32 represents the first of February and we can figure out that
February 1st fell on a Saturday.
Javascript (and most languages) handle dates exactly as described above, only in
much grander fashion. Theepoch or starting point of Javascript's date system isn't
January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it
doesn't count just days! No Javascript counts the number of milliseconds that have
passed since January 1, 1970 and presently that number is 1,407,152,039,648.
Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers
indicate dates after 1970 and negative numbers indicate dates prior to 1970. For
instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript
counts in milliseconds and there are 1000 milliseconds in a single second so -1000
represents 1 second.
By a great coincidence Unix also uses January 1, 1970 as it's epoch date which means
a timestamp in Javascript will match a timestamp on your server as long as you take
some care with the timezones!
It will be quite a while before humanity has to worry about running out of dates!
Javascript can readily handle around 285,616 years on either side of the 1970 epoch.
Creating A New Date (Parsed)
To create a new Date all you have to do is to ask for one!
var myFirstDate = new Date();
This will create a new date object and since we did not specify a specific date or time,
the date will be equal to the instant it was created.
The Javascript Date Object has a very powerful date parser. While there are several
ways to create and set Dates. The one you're most likely to use is simply to specify
the date itself, as a string, when creating a new date.
var myDate = new Date('January 16, 1988');
Since we didn't specify a time the Date which is created will be for midnight in the
browser's timezone on January 16, 1988.
var myDate = new Date('January 16, 1988 2:54:16 pm');
Here we specify a specific time (note that there's a space between the time and pm).
Since we didn't specify a timezone the browser will use the user's timezone. We could
also have used millitary time (14:54:16).
Here we'll actually specify a time zone GMT in this case and below we'll print it out.
var myDate = new Date('January 16, 1988 2:54:16 pm GMT');
Sat Jan 16 1988 15:54:16 GMT+0100 (W. Central Africa Standard Time)
Unless you actually live in the Greenwich Mean Timezone, the date requested and the
date printed are unlikely to match. The created date is actually 2:54:16 in the GMT
timezone, however when we printed the date out, since we didn't specify anything
special, the date was printed in the Browser's time zone so the browser did a little
conversion for us to ensure the time we printed was the ACTUAL time relative to the
browser.
That's a little confusing so let's try for something different. Every New Years Eve, the
city of New York holds a big celebration and the ball is dropped at precisely midnight
in the eastern timezone. So lets create a date for that event.
var myDate = new Date('January 1, 2000 EST');
Since we didn't specify a time, Javascript will assume midnight for us, we did specify a
time zone so the actual time will be midnight in the eastern time zone.
Now when we print the date out we'll get that little timezone conversion and you can
see what time the ball will be dropping in your timezone! (of course people in the
eastern timezone will see the correct time).
Sat Jan 01 2000 06:00:00 GMT+0100 (W. Central Africa Standard Time)
Creating A New Date (arguments)
You can also create a new date by passing the date values as arugments to the Date
object. The arguments are Year, Month, Date and optionally hours, minutes, seconds,
and milliseconds. The first argument, year, is special. If it's a string the Date object
will try to parse it (see previous section), if it's a long integer it will try to use it as a
julian number. If there are more than one argument it will build the date from your
supplied arguments.
var d1 = new Date('January 1, 1970'); // Date as a parse
var d2 = new Date(0); // Date as a julian number
var d3 = new Date(1970, 0, 1); // Date as arguments
Notice we use zero as the month when creating d3, that's because Javascript months
go from 0 to 11 where January is zero. This is a pretty big gotcha if you're not careful!
The argument list is as follows
dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);
Working With Julian Day Numbers
Working with Julian Dates requires division and modulus. Division will discard the
portion of the date you no longer need and modulus (which is the remainder of
division) will return the portion of the date you are looking for.
Most people don't need milliseconds when doing date calculation, so we just divide
the Julian Date Number by 1,000. So if we have a Julian Day Number of
1,177,303,066,354 then dividing this by 1,000 will give us a day number of
1,177,303,066 -- a number which no longer holds information about the milliseconds
in the date.
To get the number of seconds this represents, we take the modulus of 60 because
there are 60 seconds in a minute.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
Now that we have the number of seconds we discard the seconds from the Julian date
by dividing it by 60.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
So now our day number has been stripped of milliseconds and seconds. We can find
out how many minutes the number represents by taking the modulus of 60 since there
are 60 minutes in an hour.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
And we can discard the minutes from the original number by dividing it by 60. What
remains are hours and days. We can get the hours by taking the modulus of 24 since
there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,
leaving only the number of days.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
dayNumber = dayNumber/60; // dayNumber = 327,028
var hours = dayNumber % 24; // hours = 4
dayNumber = dayNumber/24 // dayNumber = 13,626
Or 13,624 days between January 1, 1970 and Mon Apr 23 2007 05:37:46 GMT+0100
(W. Central Africa Standard Time)
Countdown Timers In Javascript
In the previous section we broke a day number out into its component milliseconds,
seconds, minutes, hours, and days. The number we used was the number of
milliseconds that had elapsed since January 1, 1970. But we could just as easily have
used another date. Lets take the difference between now and the end of the year.
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
This code creates two julian dates, now and newYear. By
subtracting now from newYear we get an integer which represents the difference
between the two dates, specifically: 12,914,813,502.
We can use division and modulus to extract the time from this number just like we did
in the previous section only now we're computing the difference between now and the
new year instead of a date and January 1, 1970.
This article is generating now and newYear in real-time so the values below are the
actual values until the new year!
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
This gives us a value of 149 Days, 11 hours, 26 minutes, 53 seconds, until Thu Jan 01
2015 00:00:00 GMT+0100 (W. Central Africa Standard Time).
Making a Timer
In the example above now is equal to the instant it is created while newYear is a
constant value, always equal to January 1 of next year. So it's actually very easy to
make a timer. All we have to do is turn the code above into a function, set up a
setTimeout command, and create a html division somewhere on the page to hold our
timer. Here's the new code!


<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyNewYear() {
var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);

// We'll build a display string instead of doing document.writeln
var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
outStr+= ' minutes, ' + seconds + ' seconds until the new year!';
// Insert our display string into the countdown span.
document.getElementById('countdown').innerHTML=outStr;
// call this function again in exactly 1 second.
setTimeout("happyNewYear()",1000);
}
// call the countdown function (will start the timer)
happyNewYear();
</script>
When the function is called (every second), now is always set to the current, ever
advancing date, while the newYear always remains a constant. So the function works
to countdown the passing time to the destination date (new year).
And here's the result!
Does the time appear a bit off? Maybe because right now you're in Daylight time and
the new year is in daylight savings time! If this is the case, once everyone falls back
the timer will again be in sync with your expectations!
Making A Clock
Making a clock is very similar to making a countdown timer. All we have to do is to
create a new date and get it's hours, minutes, and seconds.
<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>
<script type="text/javascript">
function clock() {
var now = new Date();
var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
document.getElementById('clockDiv').innerHTML=outStr;
setTimeout('clock()',1000);
}
clock();
</script>
And the result (in military time):
Getting The Number Of Days In A Month
Javascript has a little quirk where a date of zero will set the date to be the last day of
the previous month. Likewise is there are 30 days in a month and you set a date of 31
it will be the 1st day of the next month, a date of 40 would be the 10th day of the
next month. This can lead to some very weird funkiness if you're not careful but we
can definitely exploit this for a useful prototype which will give us the number of days
in a specific month. We'll do this up as a prototype so it's available to all our Dates.
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
var d = new Date();
document.writeln('Number of days in this month: '+d.daysInMonth());
And the result (live!):
Getting The Name Of The Day And Month
While the Javascript Date Object has many useful features, one glaring oversight is
that when you ask it for the day or month it will return only the numerical
representation. This is easy enough to fix with prototypes however.
Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Mon
day', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; if (shortName) {
return Days[this.getDay()].substr(0,3); } else { return Days[this.getDay()];
} } Date.prototype.getMonthName = function() { return ['January', 'Februar
y', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'D
ecember'][this.getMonth()]; }
These two methods are pretty simple to use. If you want the month name just do
var d = new Date(); month = d.getMonthName();
If you want the name of the day, do
var d = new Date(); day = d.getDayName();
If you'd like the three character day name (mon/tue/wed, etc) then pass an argument
to getDayName. As long as the argument isn't false, null or any other falsey value the
name will be shortened to its three letter equivalent.
var d = new Date(); day = d.getDayName(true);
< Confirm Command, Combining conditions & While loop