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/

Basic JavaScript Tutorial

Embed Size (px)

DESCRIPTION

This article is the first part of a series of articles on using JavaScript tools. Today, JavaScript is a very powerful language that can be used to build web apps, mobile apps, and even some pc games — perhaps a bit faster than you would build them otherwise. New libraries have emerged in the web industry to address the challenges of JavaScript — libraries such as JQuery, Prototype and many others have been released. Today, a popular question asked by many is — should i learn the libraries such as jQuery or learn basic JavaScript. The truth is that the libraries help you to create faster, responsive JavaScript, but there are still times when your basic knowlege of JavaScript will be called into question. It is for this reason that I have created this eBook, to assist newbies learn JavaScript.

Citation preview

Page 1: Basic JavaScript Tutorial

COURSE OUTLINEThe aim of this class is to teach beginners without any knowlege of JavaScript how touse JavaScript directly. This will prepare beginners for libraries such as jQuery andother real-life work with JavaScript..

1. Welcome to JavaScriptExercise 1: Introduction to JavaScriptExercise 2: Writing Javascript CodeExercise 3: Writing Javascript Code :: Coding ConventionsExercise 4: Write Javascript: the Script ElementExercise 5: Javascript & DOM

2. JavaScript Alert Box & Math RulesExercise 1: Display messages with alertExercise 2: Math Rules: Order of operation math rulesExercise 3: The Javascript Maths Object

3. Working With Variables, Strings & Prompt DialogVariables: Store data with variablesPrompt Box: Ask questions with promptAdding Strings: Joining strings and numbers with +

4. If Statements, Boolean values & Null valuesCheck user responses with if statementsBoolean values: true & falseNull value: The special value null

5. Confirm Command, Combining conditions & While loopThe confirm commandCombining conditions with && and ||While loop: Repeat code with while loops

6. JavaScript Functions, Arrays & DatesString functions in JavaScriptJavaScript FunctionsWorking With ArraysWorking With Dates

PRE-REQUISITESThis course requires you to have basic knowlege of HTML (HyperText MarkupLanguage) and to be able to create HTML pages with a plain text editor such asnotepad.

AN ALTERNATIVE JAVASCRIPT TESTER/DEBUGGERThere are many ways to run javascript, I created a special window-based editor thatcan aid your learning javascript, it is free and can be downloaded fromhttp://sourceforge.net/projects/javascripteditor/

Page 2: Basic JavaScript Tutorial

AUTHORThis tutorial was brought to you by Anthony Ogundipe, you can find out more aboutme by visiting http://www.dhtmlextreme.net or http://github.com/dhtml

Page 3: Basic JavaScript Tutorial

Introduction to JavascriptJavascript has lots of uses, it is not only used to develop websites. This JavascriptEditor that was introduced in this tutorial is a windowssoftware, but javascript code was used in 95% of its development.Javascript can also be used to develop games (you can check this link as anexample 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 isalso 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 notnecessarily mean you will understand javascript (i use both languages so i knowthis 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, somany structures from those languages apply to JavaScript as well.

3. JavaScript does not have classes; instead, the class functionality is accomplishedby object prototypes.

4. Javascript functions are objects, giving functions the capacity to hold executablecode and be passed around like any other object.

5. Javascript has lots of uses, it is not only used to develop websites. This JavascriptEditor that was introduced in this tutorial is a windows software, but javascriptcode was used in 95% of its development.

6. Javascript is exclusively a client-sided language, this means that it must first bedownloaded 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 outputif any is sent to the client.

NEXT: Writing Javascript Code

< back to basics course outline

Page 4: Basic JavaScript Tutorial

Writing Javascript CodeJavascript 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 pagevarious 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 indirectlyexample.jsalert('Welcome to Javascript');

sample.html<html><head><title>Javascript Example</title><script src='example.js'></script></head><body>My web page</body></html>

Page 5: Basic JavaScript Tutorial

NEXT: Javascript Coding Conventions

< Introduction to Javascript

Page 6: Basic JavaScript Tutorial

Javascript Coding ConventionsI am going to reference http://msdn.microsoft.com/en-us/library/ie/cte3c772In this subsection, we are going to be looking at javascript as a programminglanguage. Most of the terminologies here will be explained as we delve more into thelanguage. Like many other programming languages, JavaScript is organized into statements,blocks consisting of related sets of statements, and comments. Within a statementyou can use variables, strings, numbers, and expressions.A JavaScript program is a collection of statements. JavaScript statementscombine expressions in such a way that they carry out one complete task.

How to write statements in javascriptA 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 writtenover two or more lines.Also, two or more statements can be written on the same line by separating themwith semicolons. In general, each new line begins anew statement. It is a good idea to terminate your statements explicitly. You do thiswith the semicolon ( ; ), which is the JavaScript statementtermination character.Here are two examples of JavaScript statements.The sentences after the // characters arecomments, which are explanatory remarks in theprogram.

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 ablock. Statements grouped into a block can generally be treated as a single statement. Thismeans 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 singlestatements within a block end insemicolons, but the block itself does not. An example script:

Page 7: Basic JavaScript Tutorial

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 pastethis code into the Javascript Editor to see the output.You do not need to understand these codes yet, we are only introducing how thecodes are written.

NEXT: The Script Element

< Writing Javascript Code

Page 8: Basic JavaScript Tutorial

The Script ElementWhen you want to use JavaScript on a website it has to be included within a SCRIPTelement:<!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 ScriptsIf you want to link to an external script file then simply add an SRC attribute to yourSCRIPT element corresponding to its location. It's normally a better idea to haveseperate script files than to write code inline as it means the browser can cache thefile. 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

Page 9: Basic JavaScript Tutorial

Javascript & DOMI think it will be good to introduce DOM at this point for reference sake, if you do notunderstand all these, dont stress yourself, as the class goes on, we will makereferences back to this and it will all make sense.The Document Object Model, normally abbreviated to DOM, is the API (applicationinterface) through which JavaScript interacts with content within a website. JavaScriptand the DOM are usually seen as a single entity since JavaScript is most commonlyused for this purpose (interacting with content on the web). The DOM API is used toaccess, 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 ithas 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 aparagraph 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 yourparagraph 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 theDOM hierarchy/tree).=> Also note that element attributes are DOM nodes themselves.

Most importantly: Each layout engine has a slightly differentimplementation of the DOM standard. For example, the Firefox webbrowser, which uses the Gecko layout engine, has quite a goodimplementation (although, not entirely inline with the W3C specification)but Internet Explorer, which uses the Trident layout engine is known for it'sbuggy and incomplete implementation; a cause of much anguish within theweb 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 problemand to make javascript easier to use.

The images below show two different outlines of the typical DOM hierarchy

Page 10: Basic JavaScript Tutorial

(Simplified)

DOM ILLUSTRATION 1: Flow Chart

DOM ILLUSTRATION 2: Tree View

NEXT: Display messages with alert

< The Script Element

Page 11: Basic JavaScript Tutorial

Display messages with alertAn alert box is often used if you want to make sure information comes through to theuser. 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 windowself.alert('message') // reference to current windowtop.alert('message') // top-level framesetparent.alert('message') // parent frame in a frameset

Examples:alert('I am an alert box!');

NEXT: Math Rules: Order of operation math rules

< Javascript & DOM

Page 12: Basic JavaScript Tutorial

Math Rules: Order of operation math rulesThe simplest way I can explain how javascript handles mathematics is byusing the popular bodmas rules.B -Brackets firstO - 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 meansthat 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

Page 13: Basic JavaScript Tutorial

The Javascript Maths ObjectMath is a built-in object that has properties and methods for mathematical constantsand functions. Not a function object.You can use it to perform other tasks such as get the value of PI (as in length of acycle 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 64document.write(Math.sqrt(64)); //answer 8

Example 3: Calculate the sine of 90document.write(Math.sin(90));

Example 4: Calculate the cosine of 90document.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

Page 14: Basic JavaScript Tutorial

Store Data With VariablesI 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 VariablesAs with algebra, JavaScript variables can be used to hold values (x = 5) orexpressions (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,enumexport,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

Page 15: Basic JavaScript Tutorial

NEXT: Prompt Box: Ask questions with prompt

< The Javascript Maths Object

Page 16: Basic JavaScript Tutorial

Prompt Box: Ask questions with promptThe Window.prompt() displays a dialog with an optional messageprompting 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 beomitted 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 isan optional parameter. Note that in Internet Explorer 7 and 8, if you do not providethis 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 shallbe treated in a later chapter.var sign = prompt('What is your sign?');if (sign == 'scorpio') {alert('Wow! I am a Scorpio too!');}

Page 17: Basic JavaScript Tutorial

NEXT: Adding Strings: Joining strings and numbers with +

< Store Data With Variables

Page 18: Basic JavaScript Tutorial

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

Page 19: Basic JavaScript Tutorial

Exercise 1: Check user responses with if statementsOne of the most important features of a computer language is the capability to testand compare values. This allows your scripts to behave differently based on thevalues of variables, or based on input from the user.

The if statement is the main conditional statement in JavaScript. This statementmeans much the same in JavaScript as it does in English—for example, here is atypical 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 anexample 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 alertmessage. Otherwise, it does nothing.

If you use an if statement like the preceding example, you can use a single statementas the action. You can also use multiple statements for the action by enclosing themin 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, itdisplays a message and sets a back to 0.

Conditional OperatorsWhile the action part of an if statement can include any of the JavaScript statementsyou've already learned (and any others, for that matter), the condition part of thestatement uses its own syntax. This is called a conditional expression.

Page 20: Basic JavaScript Tutorial

A conditional expression includes two values to be compared (in the precedingexample, the values were a and 1). These values can be variables, constants, or evenexpressions in themselves.

Note:Either side of the conditional expression can be a variable, a constant, or anexpression. You can compare a variable and a value, or compare two variables. (Youcan compare two constants, but there's usually no reason to.)

Between the two values to be compared is a conditional operator. This operator tellsJavaScript how to compare the two values. For instance, the == operator is used totest whether the two values are equal. A variety of conditional operators areavailable:

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 herevar x = 5;if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 3b: Note that x is a string herevar 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 andvariable types, a different result will be seen

Example 4a: Note that x is an integer here

Page 21: Basic JavaScript Tutorial

var x = 5;if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 4b: Note that x is a string herevar x = '5';if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 5: using comparisonvar 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 assigninga value to a variable, and == when comparing values. Confusing these two is one ofthe most common mistakes in JavaScript programming.

NEXT: Boolean values: true & false

< Joining strings and numbers with +

Page 22: Basic JavaScript Tutorial

Exercise 2: Boolean values: true & falseBoolean 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 inif() statements.

In Boolean logic, a statement can have two values, true or false. When using Booleanlogic in philosophy, the statement can be a sentence, likeIt rains today.

In more down-to-earth applications like JavaScript, a statement is something likex == 4

Both statements can be either true or false. When writing a program it is oftennecessary 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 awhole 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 aregetting 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 aregetting wet is true OR if both statements are true.

This is also very useful when writing programs. For instance, suppose you want to dosomething 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

Page 23: Basic JavaScript Tutorial

Null value: The special value nullJavascript 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

Page 24: Basic JavaScript Tutorial

Exercise 1: The confirm commandThis is used to confirm a user about certain action, and decide between two choicesdepending 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, andFALSE when cancel is clicked.Example:var x=window.confirm('Are you sure you are ok?');if (x)window.alert('Good!');elsewindow.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');}

Page 25: Basic JavaScript Tutorial

NEXT: Combining conditions with && and ||

< Null value: The special value null

Page 26: Basic JavaScript Tutorial

Exercise 2: Combining conditions with && and ||We have looked at the comparison operators above (>,<,==,=== etc), now, wewant 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 trueif ((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 trueif ((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 andfalse 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 resultif ((20 != 20) && (50 != 200)) {alert('this block will not run because 20 is 20 and cannot be anything else');}

Javascript Conditional OperatorJavaScript also contains a conditional operator that assigns a value to a variablebased on some condition.Syntax: variablename = (condition) ? value1:value2

Consider this statement:

Page 27: Basic JavaScript Tutorial

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 thesame result:

var age=15;var voteable = (age < 18) ? 'Too young':'Old enough';alert(voteable);

Page 28: Basic JavaScript Tutorial

NEXT: While loop: Repeat code with while loops

< The confirm command

Page 29: Basic JavaScript Tutorial

While loop: Repeat code with while loopsLoops 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 sowe end this tutorial.

NEXT: String functions in JavaScript

< Combining conditions with && and ||

Page 30: Basic JavaScript Tutorial

Exercise 1: String functions in JavaScriptJavaScript 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” withinthe string.

var message="jquery4u"; alert(message.charAt(1)); //alerts "q"

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into theexisting 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 specifiedsequence of Unicode values (arguments c1, c2 etc). Method of String object, notString instance. For example: String.fromCharCode().

alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyzalert(String.fromCharCode(72,69,76,76,79)); //output: HELLO

5. indexOf(substr, [start]) Searches and (if found) returns the index number of thesearched character or substring within the string. If not found, -1 is returned. “Start” isan optional argument specifying the position within string to begin the search. Defaultis 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 ofthe searched character or substring within the string. Searches the string from end tobeginning. If not found, -1 is returned. “Start” is an optional argument specifying theposition within string to begin the search. Default is string.length-1.

Page 31: Basic JavaScript Tutorial

//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 regularexpression. It returns an array of information or null if no match is found.

//match(regexp) //select integers onlyvar 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 regularexpression (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.

Page 32: Basic JavaScript Tutorial

//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 ifnone 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 specifieddelimiter, and returns an array containing each element. The optional “limit” is aninteger 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 ifomitted, 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

Page 33: Basic JavaScript Tutorial

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 tolowercase.

//toLowerCase()var myString = 'JAVASCRIPT ROX';myString = myString.toLowerCase();alert(myString)//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted touppercase.

//toUpperCase()var myString = 'javascript rox';myString = myString.toUpperCase();alert(myString)//output: JAVASCRIPT ROX

NEXT JavaScript Functions

< While loop: Repeat code with while loops

Page 34: Basic JavaScript Tutorial

Exercise 1: String functions in JavaScriptJavaScript 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” withinthe string.

var message="jquery4u"; alert(message.charAt(1)); //alerts "q"

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into theexisting 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 specifiedsequence of Unicode values (arguments c1, c2 etc). Method of String object, notString instance. For example: String.fromCharCode().

alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyzalert(String.fromCharCode(72,69,76,76,79)); //output: HELLO

5. indexOf(substr, [start]) Searches and (if found) returns the index number of thesearched character or substring within the string. If not found, -1 is returned. “Start” isan optional argument specifying the position within string to begin the search. Defaultis 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 ofthe searched character or substring within the string. Searches the string from end tobeginning. If not found, -1 is returned. “Start” is an optional argument specifying theposition within string to begin the search. Default is string.length-1.

Page 35: Basic JavaScript Tutorial

//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 regularexpression. It returns an array of information or null if no match is found.

//match(regexp) //select integers onlyvar 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 regularexpression (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.

Page 36: Basic JavaScript Tutorial

//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 ifnone 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 specifieddelimiter, and returns an array containing each element. The optional “limit” is aninteger 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 ifomitted, 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

Page 37: Basic JavaScript Tutorial

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 tolowercase.

//toLowerCase()var myString = 'JAVASCRIPT ROX';myString = myString.toLowerCase();alert(myString)//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted touppercase.

//toUpperCase()var myString = 'javascript rox';myString = myString.toUpperCase();alert(myString)//output: JAVASCRIPT ROX

Page 38: Basic JavaScript Tutorial

Exercise 2: Creating JavaScript FunctionsJavaScript also allows us to create custom functions to solve our everydayfunctionalities. 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 inthe two examples below, you will not get any result because the functions were notcalled 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 functionsvar 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 functionthat will alert the first and last name of a person.

Example 5:

Page 39: Basic JavaScript Tutorial

function myname(first,last) {alert('Your full name is '+first+' '+last);}myname('Tony', 'Olawale');

Example 6: A function can also return a resultfunction myname(first,last) {var r='Your full name is '+first+' '+last;return r;}var fullname=myname('Tony', 'Olawale');alert(fullname);

Page 40: Basic JavaScript Tutorial

Exercise 3: Working With ArraysAn Array is an enumerated list of variables. It's a programming construct that allowsprogrammers 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, allowingfor 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 ArrayMost 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 wantto 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 willautomatically increase the size of the Array as needed, as you add items into theArray. Creating an Array with brackets instead of with thenew constructor avoids a bit

Page 41: Basic JavaScript Tutorial

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 elements. 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 addmore than one item then badArray would be initialized correctly since Javascript wouldthen be smart enough to know that you were initializing the array instead of statinghow many elements you wanted to add.

Since the new constructor is not necessary with Arrays and there's a slight chance ofunintended results by using the new constructor, it's recommended you not use newArray() to create an Array.

Initializing An ArrayYou 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 output: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March

Storing Data In An ArrayAn array can store anything you can assign to a variable: booleans, numbers, strings,functions, objects, other Arrays, even regular expressions…

Page 42: Basic JavaScript Tutorial

var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! document.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.writeln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.writeln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true

Multi-Dimensional ArraysSince an Array can store other Arrays you can get the benefit of multi-dimensionarrays.

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 firstelement in the array y. If we ask for the value of y[0] it will return the contents of x asa 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 ReferenceArrays are passed to functions by reference, or as a pointer to the original. This meansanything 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]); // Will output: changed

Javascript Arrays Are Assigned By ReferenceAssigning an Array to a new variable creates a pointer to the original Array. Forinstance…

Page 43: Basic JavaScript Tutorial

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray; newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed

Passing Arrays As ValuesTo 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.slice(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'; } passedByReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one

Array.lengthEvery Array has a length property. This always contains the number of elements in thearray. Since Arrays always start at zero, the length property is convenient for loopssince it will always be one greater than the actual index. For instance if the Array has10 elements then the indexes will be 0-9, so as long as our counter is less than theArray.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 itemsare undefined the length property will still count them because it's always one higherthan 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>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 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 100elements in an array and set the length to 50, Javascript will truncate the last 50elements from the array (effectively deleting them). If you have 10 elements in anarray and set Array.length to 100 then the length of the array will be expanded to100, creating 90 undefined elements after the original 10 items.

Javascript Does Not Support Associative ArraysAn associative array is an array which uses a string instead of a number as an index.

Page 44: Basic JavaScript Tutorial

var normalArray = []; normalArray[1] = 'This is an enumerated array'; alert(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… Allarrays in Javascript are objects and Javascript's object syntax gives a basic emulationof an associative Array. For this reason the example code above will actually work. Bewarned 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 andmethods, just like .length, .sort(), .splice(), and all the other built-in properties andmethods.

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) { document.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second, three:Third };

In the above example, associativeArray.length will be zero because we didn't actuallyput anything into the Array, we put it into associativeArray'sobject. associativeArray[0] will be undefined.

The loop in the above example will also pick up any methods, properties, andprototypes which have been added to the array and not just your data. A lot ofproblems people have with the Prototype library is that their associative arrays breakbecause Prototype adds a few useful Prototype functions to the Array object and for iin x loops pick up those additional methods. That's the pitfal of using Array/objects asa poor man's associative array.

As a final example, the previous code will work regardless of whether you defineassociativeArray 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.

Page 45: Basic JavaScript Tutorial

Exercise 4: Working With DatesOf all the core Javascript objects, I find Dates to be the most fascinating. Once youlearn a few small tricks everything about Javascript Dates just seem to fall into placeand you find that there's really nothing at all that you can't do with them, quickly, andeasily.

This reference will cover the Javascript Date Object, how it stores Dates, how you canmanipulate them, create calendars, countdown timers, prototype them to add yourown functionality, as well as provide a complete method reference.

Julian DatesJulian Dates are a method of referencing time and dates based on how much time haspassed since an arbitrary number in the past. For instance, 215 days have presentlypassed this year. If we know that January 1 begins on a Wednesday , then we knowthat day 2 represents a Thursday in January. If we know there are 31 days in Januarythen we know that day 32 represents the first of February and we can figure out thatFebruary 1st fell on a Saturday.

Javascript (and most languages) handle dates exactly as described above, only inmuch grander fashion. Theepoch or starting point of Javascript's date system isn'tJanuary 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and itdoesn't count just days! No Javascript counts the number of milliseconds that havepassed 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 numbersindicate dates after 1970 and negative numbers indicate dates prior to 1970. Forinstance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascriptcounts in milliseconds and there are 1000 milliseconds in a single second so -1000represents 1 second.

By a great coincidence Unix also uses January 1, 1970 as it's epoch date which meansa timestamp in Javascript will match a timestamp on your server as long as you takesome 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 severalways to create and set Dates. The one you're most likely to use is simply to specify

Page 46: Basic JavaScript Tutorial

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 thebrowser'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 couldalso 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 thedate printed are unlikely to match. The created date is actually 2:54:16 in the GMTtimezone, however when we printed the date out, since we didn't specify anythingspecial, the date was printed in the Browser's time zone so the browser did a littleconversion for us to ensure the time we printed was the ACTUAL time relative to thebrowser.

That's a little confusing so let's try for something different. Every New Years Eve, thecity of New York holds a big celebration and the ball is dropped at precisely midnightin 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 atime 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 cansee what time the ball will be dropping in your timezone! (of course people in theeastern 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 Dateobject. 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 objectwill try to parse it (see previous section), if it's a long integer it will try to use it as ajulian number. If there are more than one argument it will build the date from yoursupplied arguments.

Page 47: Basic JavaScript Tutorial

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 monthsgo 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 NumbersWorking with Julian Dates requires division and modulus. Division will discard theportion of the date you no longer need and modulus (which is the remainder ofdivision) will return the portion of the date you are looking for.

Most people don't need milliseconds when doing date calculation, so we just dividethe Julian Date Number by 1,000. So if we have a Julian Day Number of1,177,303,066,354 then dividing this by 1,000 will give us a day number of1,177,303,066 -- a number which no longer holds information about the millisecondsin the date.

To get the number of seconds this represents, we take the modulus of 60 becausethere 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 dateby 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 findout how many minutes the number represents by taking the modulus of 60 since thereare 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. Whatremains are hours and days. We can get the hours by taking the modulus of 24 sincethere are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,leaving only the number of days.

Page 48: Basic JavaScript Tutorial

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 JavascriptIn 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 ofmilliseconds that had elapsed since January 1, 1970. But we could just as easily haveused 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. Bysubtracting now from newYear we get an integer which represents the differencebetween the two dates, specifically: 12,914,813,502.

We can use division and modulus to extract the time from this number just like we didin the previous section only now we're computing the difference between now and thenew year instead of a date and January 1, 1970.

This article is generating now and newYear in real-time so the values below are theactual 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 012015 00:00:00 GMT+0100 (W. Central Africa Standard Time).

Page 49: Basic JavaScript Tutorial

Making a TimerIn the example above now is equal to the instant it is created while newYear is aconstant value, always equal to January 1 of next year. So it's actually very easy tomake a timer. All we have to do is turn the code above into a function, set up asetTimeout command, and create a html division somewhere on the page to hold ourtimer. 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>

Page 50: Basic JavaScript Tutorial

When the function is called (every second), now is always set to the current, everadvancing date, while the newYear always remains a constant. So the function worksto 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 andthe new year is in daylight savings time! If this is the case, once everyone falls backthe timer will again be in sync with your expectations!

Making A ClockMaking a clock is very similar to making a countdown timer. All we have to do is tocreate 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 MonthJavascript has a little quirk where a date of zero will set the date to be the last day ofthe previous month. Likewise is there are 30 days in a month and you set a date of 31it will be the 1st day of the next month, a date of 40 would be the 10th day of thenext month. This can lead to some very weird funkiness if you're not careful but wecan definitely exploit this for a useful prototype which will give us the number of daysin 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!):

Page 51: Basic JavaScript Tutorial

Getting The Name Of The Day And MonthWhile the Javascript Date Object has many useful features, one glaring oversight isthat when you ask it for the day or month it will return only the numericalrepresentation. This is easy enough to fix with prototypes however.

Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Monday', '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', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][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 argumentto getDayName. As long as the argument isn't false, null or any other falsey value thename will be shortened to its three letter equivalent.

var d = new Date(); day = d.getDayName(true);

NEXT: Working With Arrays

< String functions in JavaScript

Page 52: Basic JavaScript Tutorial

Exercise 1: String functions in JavaScriptJavaScript 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” withinthe string.

var message="jquery4u"; alert(message.charAt(1)); //alerts "q"

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into theexisting 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 specifiedsequence of Unicode values (arguments c1, c2 etc). Method of String object, notString instance. For example: String.fromCharCode().

alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyzalert(String.fromCharCode(72,69,76,76,79)); //output: HELLO

5. indexOf(substr, [start]) Searches and (if found) returns the index number of thesearched character or substring within the string. If not found, -1 is returned. “Start” isan optional argument specifying the position within string to begin the search. Defaultis 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 ofthe searched character or substring within the string. Searches the string from end tobeginning. If not found, -1 is returned. “Start” is an optional argument specifying theposition within string to begin the search. Default is string.length-1.

Page 53: Basic JavaScript Tutorial

//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 regularexpression. It returns an array of information or null if no match is found.

//match(regexp) //select integers onlyvar 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 regularexpression (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.

Page 54: Basic JavaScript Tutorial

//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 ifnone 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 specifieddelimiter, and returns an array containing each element. The optional “limit” is aninteger 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 ifomitted, 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

Page 55: Basic JavaScript Tutorial

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 tolowercase.

//toLowerCase()var myString = 'JAVASCRIPT ROX';myString = myString.toLowerCase();alert(myString)//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted touppercase.

//toUpperCase()var myString = 'javascript rox';myString = myString.toUpperCase();alert(myString)//output: JAVASCRIPT ROX

Page 56: Basic JavaScript Tutorial

Exercise 2: Creating JavaScript FunctionsJavaScript also allows us to create custom functions to solve our everydayfunctionalities. 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 inthe two examples below, you will not get any result because the functions were notcalled 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 functionsvar 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 functionthat will alert the first and last name of a person.

Example 5:

Page 57: Basic JavaScript Tutorial

function myname(first,last) {alert('Your full name is '+first+' '+last);}myname('Tony', 'Olawale');

Example 6: A function can also return a resultfunction myname(first,last) {var r='Your full name is '+first+' '+last;return r;}var fullname=myname('Tony', 'Olawale');alert(fullname);

Page 58: Basic JavaScript Tutorial

Exercise 3: Working With ArraysAn Array is an enumerated list of variables. It's a programming construct that allowsprogrammers 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, allowingfor 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 ArrayMost 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 wantto 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 willautomatically increase the size of the Array as needed, as you add items into theArray. Creating an Array with brackets instead of with thenew constructor avoids a bit

Page 59: Basic JavaScript Tutorial

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 elements. 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 addmore than one item then badArray would be initialized correctly since Javascript wouldthen be smart enough to know that you were initializing the array instead of statinghow many elements you wanted to add.

Since the new constructor is not necessary with Arrays and there's a slight chance ofunintended results by using the new constructor, it's recommended you not use newArray() to create an Array.

Initializing An ArrayYou 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 output: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March

Storing Data In An ArrayAn array can store anything you can assign to a variable: booleans, numbers, strings,functions, objects, other Arrays, even regular expressions…

Page 60: Basic JavaScript Tutorial

var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! document.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.writeln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.writeln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true

Multi-Dimensional ArraysSince an Array can store other Arrays you can get the benefit of multi-dimensionarrays.

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 firstelement in the array y. If we ask for the value of y[0] it will return the contents of x asa 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 ReferenceArrays are passed to functions by reference, or as a pointer to the original. This meansanything 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]); // Will output: changed

Javascript Arrays Are Assigned By ReferenceAssigning an Array to a new variable creates a pointer to the original Array. Forinstance…

Page 61: Basic JavaScript Tutorial

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray; newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed

Passing Arrays As ValuesTo 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.slice(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'; } passedByReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one

Array.lengthEvery Array has a length property. This always contains the number of elements in thearray. Since Arrays always start at zero, the length property is convenient for loopssince it will always be one greater than the actual index. For instance if the Array has10 elements then the indexes will be 0-9, so as long as our counter is less than theArray.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 itemsare undefined the length property will still count them because it's always one higherthan 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>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 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 100elements in an array and set the length to 50, Javascript will truncate the last 50elements from the array (effectively deleting them). If you have 10 elements in anarray and set Array.length to 100 then the length of the array will be expanded to100, creating 90 undefined elements after the original 10 items.

Javascript Does Not Support Associative ArraysAn associative array is an array which uses a string instead of a number as an index.

Page 62: Basic JavaScript Tutorial

var normalArray = []; normalArray[1] = 'This is an enumerated array'; alert(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… Allarrays in Javascript are objects and Javascript's object syntax gives a basic emulationof an associative Array. For this reason the example code above will actually work. Bewarned 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 andmethods, just like .length, .sort(), .splice(), and all the other built-in properties andmethods.

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) { document.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second, three:Third };

In the above example, associativeArray.length will be zero because we didn't actuallyput anything into the Array, we put it into associativeArray'sobject. associativeArray[0] will be undefined.

The loop in the above example will also pick up any methods, properties, andprototypes which have been added to the array and not just your data. A lot ofproblems people have with the Prototype library is that their associative arrays breakbecause Prototype adds a few useful Prototype functions to the Array object and for iin x loops pick up those additional methods. That's the pitfal of using Array/objects asa poor man's associative array.

As a final example, the previous code will work regardless of whether you defineassociativeArray 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.

Page 63: Basic JavaScript Tutorial

Exercise 4: Working With DatesOf all the core Javascript objects, I find Dates to be the most fascinating. Once youlearn a few small tricks everything about Javascript Dates just seem to fall into placeand you find that there's really nothing at all that you can't do with them, quickly, andeasily.

This reference will cover the Javascript Date Object, how it stores Dates, how you canmanipulate them, create calendars, countdown timers, prototype them to add yourown functionality, as well as provide a complete method reference.

Julian DatesJulian Dates are a method of referencing time and dates based on how much time haspassed since an arbitrary number in the past. For instance, 215 days have presentlypassed this year. If we know that January 1 begins on a Wednesday , then we knowthat day 2 represents a Thursday in January. If we know there are 31 days in Januarythen we know that day 32 represents the first of February and we can figure out thatFebruary 1st fell on a Saturday.

Javascript (and most languages) handle dates exactly as described above, only inmuch grander fashion. Theepoch or starting point of Javascript's date system isn'tJanuary 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and itdoesn't count just days! No Javascript counts the number of milliseconds that havepassed 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 numbersindicate dates after 1970 and negative numbers indicate dates prior to 1970. Forinstance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascriptcounts in milliseconds and there are 1000 milliseconds in a single second so -1000represents 1 second.

By a great coincidence Unix also uses January 1, 1970 as it's epoch date which meansa timestamp in Javascript will match a timestamp on your server as long as you takesome 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 severalways to create and set Dates. The one you're most likely to use is simply to specify

Page 64: Basic JavaScript Tutorial

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 thebrowser'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 couldalso 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 thedate printed are unlikely to match. The created date is actually 2:54:16 in the GMTtimezone, however when we printed the date out, since we didn't specify anythingspecial, the date was printed in the Browser's time zone so the browser did a littleconversion for us to ensure the time we printed was the ACTUAL time relative to thebrowser.

That's a little confusing so let's try for something different. Every New Years Eve, thecity of New York holds a big celebration and the ball is dropped at precisely midnightin 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 atime 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 cansee what time the ball will be dropping in your timezone! (of course people in theeastern 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 Dateobject. 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 objectwill try to parse it (see previous section), if it's a long integer it will try to use it as ajulian number. If there are more than one argument it will build the date from yoursupplied arguments.

Page 65: Basic JavaScript Tutorial

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 monthsgo 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 NumbersWorking with Julian Dates requires division and modulus. Division will discard theportion of the date you no longer need and modulus (which is the remainder ofdivision) will return the portion of the date you are looking for.

Most people don't need milliseconds when doing date calculation, so we just dividethe Julian Date Number by 1,000. So if we have a Julian Day Number of1,177,303,066,354 then dividing this by 1,000 will give us a day number of1,177,303,066 -- a number which no longer holds information about the millisecondsin the date.

To get the number of seconds this represents, we take the modulus of 60 becausethere 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 dateby 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 findout how many minutes the number represents by taking the modulus of 60 since thereare 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. Whatremains are hours and days. We can get the hours by taking the modulus of 24 sincethere are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,leaving only the number of days.

Page 66: Basic JavaScript Tutorial

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 JavascriptIn 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 ofmilliseconds that had elapsed since January 1, 1970. But we could just as easily haveused 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. Bysubtracting now from newYear we get an integer which represents the differencebetween the two dates, specifically: 12,914,813,502.

We can use division and modulus to extract the time from this number just like we didin the previous section only now we're computing the difference between now and thenew year instead of a date and January 1, 1970.

This article is generating now and newYear in real-time so the values below are theactual 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 012015 00:00:00 GMT+0100 (W. Central Africa Standard Time).

Page 67: Basic JavaScript Tutorial

Making a TimerIn the example above now is equal to the instant it is created while newYear is aconstant value, always equal to January 1 of next year. So it's actually very easy tomake a timer. All we have to do is turn the code above into a function, set up asetTimeout command, and create a html division somewhere on the page to hold ourtimer. 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>

Page 68: Basic JavaScript Tutorial

When the function is called (every second), now is always set to the current, everadvancing date, while the newYear always remains a constant. So the function worksto 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 andthe new year is in daylight savings time! If this is the case, once everyone falls backthe timer will again be in sync with your expectations!

Making A ClockMaking a clock is very similar to making a countdown timer. All we have to do is tocreate 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 MonthJavascript has a little quirk where a date of zero will set the date to be the last day ofthe previous month. Likewise is there are 30 days in a month and you set a date of 31it will be the 1st day of the next month, a date of 40 would be the 10th day of thenext month. This can lead to some very weird funkiness if you're not careful but wecan definitely exploit this for a useful prototype which will give us the number of daysin 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!):

Page 69: Basic JavaScript Tutorial

Getting The Name Of The Day And MonthWhile the Javascript Date Object has many useful features, one glaring oversight isthat when you ask it for the day or month it will return only the numericalrepresentation. This is easy enough to fix with prototypes however.

Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Monday', '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', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][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 argumentto getDayName. As long as the argument isn't false, null or any other falsey value thename will be shortened to its three letter equivalent.

var d = new Date(); day = d.getDayName(true);

NEXT: Working With Dates

< JavaScript Functions

Page 70: Basic JavaScript Tutorial

Exercise 1: String functions in JavaScriptJavaScript 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” withinthe string.

var message="jquery4u"; alert(message.charAt(1)); //alerts "q"

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into theexisting 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 specifiedsequence of Unicode values (arguments c1, c2 etc). Method of String object, notString instance. For example: String.fromCharCode().

alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyzalert(String.fromCharCode(72,69,76,76,79)); //output: HELLO

5. indexOf(substr, [start]) Searches and (if found) returns the index number of thesearched character or substring within the string. If not found, -1 is returned. “Start” isan optional argument specifying the position within string to begin the search. Defaultis 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 ofthe searched character or substring within the string. Searches the string from end tobeginning. If not found, -1 is returned. “Start” is an optional argument specifying theposition within string to begin the search. Default is string.length-1.

Page 71: Basic JavaScript Tutorial

//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 regularexpression. It returns an array of information or null if no match is found.

//match(regexp) //select integers onlyvar 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 regularexpression (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.

Page 72: Basic JavaScript Tutorial

//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 ifnone 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 specifieddelimiter, and returns an array containing each element. The optional “limit” is aninteger 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 ifomitted, 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

Page 73: Basic JavaScript Tutorial

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 tolowercase.

//toLowerCase()var myString = 'JAVASCRIPT ROX';myString = myString.toLowerCase();alert(myString)//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted touppercase.

//toUpperCase()var myString = 'javascript rox';myString = myString.toUpperCase();alert(myString)//output: JAVASCRIPT ROX

Page 74: Basic JavaScript Tutorial

Exercise 2: Creating JavaScript FunctionsJavaScript also allows us to create custom functions to solve our everydayfunctionalities. 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 inthe two examples below, you will not get any result because the functions were notcalled 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 functionsvar 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 functionthat will alert the first and last name of a person.

Example 5:

Page 75: Basic JavaScript Tutorial

function myname(first,last) {alert('Your full name is '+first+' '+last);}myname('Tony', 'Olawale');

Example 6: A function can also return a resultfunction myname(first,last) {var r='Your full name is '+first+' '+last;return r;}var fullname=myname('Tony', 'Olawale');alert(fullname);

Page 76: Basic JavaScript Tutorial

Exercise 3: Working With ArraysAn Array is an enumerated list of variables. It's a programming construct that allowsprogrammers 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, allowingfor 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 ArrayMost 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 wantto 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 willautomatically increase the size of the Array as needed, as you add items into theArray. Creating an Array with brackets instead of with thenew constructor avoids a bit

Page 77: Basic JavaScript Tutorial

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 elements. 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 addmore than one item then badArray would be initialized correctly since Javascript wouldthen be smart enough to know that you were initializing the array instead of statinghow many elements you wanted to add.

Since the new constructor is not necessary with Arrays and there's a slight chance ofunintended results by using the new constructor, it's recommended you not use newArray() to create an Array.

Initializing An ArrayYou 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 output: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March

Storing Data In An ArrayAn array can store anything you can assign to a variable: booleans, numbers, strings,functions, objects, other Arrays, even regular expressions…

Page 78: Basic JavaScript Tutorial

var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! document.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.writeln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.writeln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true

Multi-Dimensional ArraysSince an Array can store other Arrays you can get the benefit of multi-dimensionarrays.

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 firstelement in the array y. If we ask for the value of y[0] it will return the contents of x asa 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 ReferenceArrays are passed to functions by reference, or as a pointer to the original. This meansanything 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]); // Will output: changed

Javascript Arrays Are Assigned By ReferenceAssigning an Array to a new variable creates a pointer to the original Array. Forinstance…

Page 79: Basic JavaScript Tutorial

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray; newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed

Passing Arrays As ValuesTo 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.slice(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'; } passedByReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one

Array.lengthEvery Array has a length property. This always contains the number of elements in thearray. Since Arrays always start at zero, the length property is convenient for loopssince it will always be one greater than the actual index. For instance if the Array has10 elements then the indexes will be 0-9, so as long as our counter is less than theArray.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 itemsare undefined the length property will still count them because it's always one higherthan 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>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 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 100elements in an array and set the length to 50, Javascript will truncate the last 50elements from the array (effectively deleting them). If you have 10 elements in anarray and set Array.length to 100 then the length of the array will be expanded to100, creating 90 undefined elements after the original 10 items.

Javascript Does Not Support Associative ArraysAn associative array is an array which uses a string instead of a number as an index.

Page 80: Basic JavaScript Tutorial

var normalArray = []; normalArray[1] = 'This is an enumerated array'; alert(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… Allarrays in Javascript are objects and Javascript's object syntax gives a basic emulationof an associative Array. For this reason the example code above will actually work. Bewarned 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 andmethods, just like .length, .sort(), .splice(), and all the other built-in properties andmethods.

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) { document.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second, three:Third };

In the above example, associativeArray.length will be zero because we didn't actuallyput anything into the Array, we put it into associativeArray'sobject. associativeArray[0] will be undefined.

The loop in the above example will also pick up any methods, properties, andprototypes which have been added to the array and not just your data. A lot ofproblems people have with the Prototype library is that their associative arrays breakbecause Prototype adds a few useful Prototype functions to the Array object and for iin x loops pick up those additional methods. That's the pitfal of using Array/objects asa poor man's associative array.

As a final example, the previous code will work regardless of whether you defineassociativeArray 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.

Page 81: Basic JavaScript Tutorial

Exercise 4: Working With DatesOf all the core Javascript objects, I find Dates to be the most fascinating. Once youlearn a few small tricks everything about Javascript Dates just seem to fall into placeand you find that there's really nothing at all that you can't do with them, quickly, andeasily.

This reference will cover the Javascript Date Object, how it stores Dates, how you canmanipulate them, create calendars, countdown timers, prototype them to add yourown functionality, as well as provide a complete method reference.

Julian DatesJulian Dates are a method of referencing time and dates based on how much time haspassed since an arbitrary number in the past. For instance, 215 days have presentlypassed this year. If we know that January 1 begins on a Wednesday , then we knowthat day 2 represents a Thursday in January. If we know there are 31 days in Januarythen we know that day 32 represents the first of February and we can figure out thatFebruary 1st fell on a Saturday.

Javascript (and most languages) handle dates exactly as described above, only inmuch grander fashion. Theepoch or starting point of Javascript's date system isn'tJanuary 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and itdoesn't count just days! No Javascript counts the number of milliseconds that havepassed 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 numbersindicate dates after 1970 and negative numbers indicate dates prior to 1970. Forinstance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascriptcounts in milliseconds and there are 1000 milliseconds in a single second so -1000represents 1 second.

By a great coincidence Unix also uses January 1, 1970 as it's epoch date which meansa timestamp in Javascript will match a timestamp on your server as long as you takesome 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 severalways to create and set Dates. The one you're most likely to use is simply to specify

Page 82: Basic JavaScript Tutorial

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 thebrowser'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 couldalso 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 thedate printed are unlikely to match. The created date is actually 2:54:16 in the GMTtimezone, however when we printed the date out, since we didn't specify anythingspecial, the date was printed in the Browser's time zone so the browser did a littleconversion for us to ensure the time we printed was the ACTUAL time relative to thebrowser.

That's a little confusing so let's try for something different. Every New Years Eve, thecity of New York holds a big celebration and the ball is dropped at precisely midnightin 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 atime 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 cansee what time the ball will be dropping in your timezone! (of course people in theeastern 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 Dateobject. 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 objectwill try to parse it (see previous section), if it's a long integer it will try to use it as ajulian number. If there are more than one argument it will build the date from yoursupplied arguments.

Page 83: Basic JavaScript Tutorial

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 monthsgo 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 NumbersWorking with Julian Dates requires division and modulus. Division will discard theportion of the date you no longer need and modulus (which is the remainder ofdivision) will return the portion of the date you are looking for.

Most people don't need milliseconds when doing date calculation, so we just dividethe Julian Date Number by 1,000. So if we have a Julian Day Number of1,177,303,066,354 then dividing this by 1,000 will give us a day number of1,177,303,066 -- a number which no longer holds information about the millisecondsin the date.

To get the number of seconds this represents, we take the modulus of 60 becausethere 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 dateby 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 findout how many minutes the number represents by taking the modulus of 60 since thereare 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. Whatremains are hours and days. We can get the hours by taking the modulus of 24 sincethere are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,leaving only the number of days.

Page 84: Basic JavaScript Tutorial

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 JavascriptIn 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 ofmilliseconds that had elapsed since January 1, 1970. But we could just as easily haveused 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. Bysubtracting now from newYear we get an integer which represents the differencebetween the two dates, specifically: 12,914,813,502.

We can use division and modulus to extract the time from this number just like we didin the previous section only now we're computing the difference between now and thenew year instead of a date and January 1, 1970.

This article is generating now and newYear in real-time so the values below are theactual 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 012015 00:00:00 GMT+0100 (W. Central Africa Standard Time).

Page 85: Basic JavaScript Tutorial

Making a TimerIn the example above now is equal to the instant it is created while newYear is aconstant value, always equal to January 1 of next year. So it's actually very easy tomake a timer. All we have to do is turn the code above into a function, set up asetTimeout command, and create a html division somewhere on the page to hold ourtimer. 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>

Page 86: Basic JavaScript Tutorial

When the function is called (every second), now is always set to the current, everadvancing date, while the newYear always remains a constant. So the function worksto 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 andthe new year is in daylight savings time! If this is the case, once everyone falls backthe timer will again be in sync with your expectations!

Making A ClockMaking a clock is very similar to making a countdown timer. All we have to do is tocreate 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 MonthJavascript has a little quirk where a date of zero will set the date to be the last day ofthe previous month. Likewise is there are 30 days in a month and you set a date of 31it will be the 1st day of the next month, a date of 40 would be the 10th day of thenext month. This can lead to some very weird funkiness if you're not careful but wecan definitely exploit this for a useful prototype which will give us the number of daysin 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!):

Page 87: Basic JavaScript Tutorial

Getting The Name Of The Day And MonthWhile the Javascript Date Object has many useful features, one glaring oversight isthat when you ask it for the day or month it will return only the numericalrepresentation. This is easy enough to fix with prototypes however.

Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Monday', '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', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][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 argumentto getDayName. As long as the argument isn't false, null or any other falsey value thename will be shortened to its three letter equivalent.

var d = new Date(); day = d.getDayName(true);

< Working With Arrays

Page 88: Basic JavaScript Tutorial

Welcome To JavaScriptIntroduction to JavaScriptWriting Javascript CodeWriting Javascript Code :: Coding ConventionsWrite Javascript: the Script ElementJavascript & DOM

Page 89: Basic JavaScript Tutorial

Exercise 1: Introduction to JavascriptJavascript has lots of uses, it is not only used to develop websites. This JavascriptEditor that was introduced in this tutorial is a windowssoftware, but javascript code was used in 95% of its development.Javascript can also be used to develop games (you can check this link as anexample 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 isalso 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 notnecessarily mean you will understand javascript (i use both languages so i knowthis 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, somany structures from those languages apply to JavaScript as well.

3. JavaScript does not have classes; instead, the class functionality is accomplishedby object prototypes.

4. Javascript functions are objects, giving functions the capacity to hold executablecode and be passed around like any other object.

5. Javascript has lots of uses, it is not only used to develop websites. This JavascriptEditor that was introduced in this tutorial is a windows software, but javascriptcode was used in 95% of its development.

6. Javascript is exclusively a client-sided language, this means that it must first bedownloaded 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 outputif any is sent to the client.

Page 90: Basic JavaScript Tutorial

Exercise 2: Writing Javascript CodeJavascript 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 pagevarious 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 indirectlyexample.jsalert('Welcome to Javascript');

sample.html

Page 91: Basic JavaScript Tutorial

<html><head><title>Javascript Example</title><script src='example.js'></script></head><body>My web page</body></html>

Page 92: Basic JavaScript Tutorial

Exercise 3: Writing Javascript Code :: Coding ConventionsI am going to reference http://msdn.microsoft.com/en-us/library/ie/cte3c772In this subsection, we are going to be looking at javascript as a programminglanguage. Most of the terminologies here will be explained as we delve more into thelanguage. Like many other programming languages, JavaScript is organized into statements,blocks consisting of related sets of statements, and comments. Within a statementyou can use variables, strings, numbers, and expressions.A JavaScript program is a collection of statements. JavaScript statementscombine expressions in such a way that they carry out one complete task.

How to write statements in javascriptA 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 writtenover two or more lines.Also, two or more statements can be written on the same line by separating themwith semicolons. In general, each new line begins anew statement. It is a good idea to terminate your statements explicitly. You do thiswith the semicolon ( ; ), which is the JavaScript statementtermination character.Here are two examples of JavaScript statements.The sentences after the // characters arecomments, which are explanatory remarks in theprogram.

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 ablock. Statements grouped into a block can generally be treated as a single statement. Thismeans 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 singlestatements within a block end insemicolons, but the block itself does not. An example script:

Page 93: Basic JavaScript Tutorial

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 pastethis code into the Javascript Editor to see the output.You do not need to understand these codes yet, we are only introducing how thecodes are written.

Page 94: Basic JavaScript Tutorial

Exercise 4: Write Javascript: the Script ElementWhen you want to use JavaScript on a website it has to be included within a SCRIPTelement:<!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 ScriptsIf you want to link to an external script file then simply add an SRC attribute to yourSCRIPT element corresponding to its location. It's normally a better idea to haveseperate script files than to write code inline as it means the browser can cache thefile. Plus you don't need to worry about any of that CDATA nonsense:<script type="text/javascript" src="my-script.js"></script>

Page 95: Basic JavaScript Tutorial

Exercise 5: Javascript & DOMI think it will be good to introduce DOM at this point for reference sake, if you do notunderstand all these, dont stress yourself, as the class goes on, we will makereferences back to this and it will all make sense.The Document Object Model, normally abbreviated to DOM, is the API (applicationinterface) through which JavaScript interacts with content within a website. JavaScriptand the DOM are usually seen as a single entity since JavaScript is most commonlyused for this purpose (interacting with content on the web). The DOM API is used toaccess, 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 ithas 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 aparagraph 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 yourparagraph 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 theDOM hierarchy/tree).=> Also note that element attributes are DOM nodes themselves.

Most importantly: Each layout engine has a slightly differentimplementation of the DOM standard. For example, the Firefox webbrowser, which uses the Gecko layout engine, has quite a goodimplementation (although, not entirely inline with the W3C specification)but Internet Explorer, which uses the Trident layout engine is known for it'sbuggy and incomplete implementation; a cause of much anguish within theweb 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 problemand to make javascript easier to use.

Page 96: Basic JavaScript Tutorial

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

Page 97: Basic JavaScript Tutorial

JavaScript Alert Box & Math RulesDisplay messages with alertMath Rules: Order of operation math rulesThe Javascript Maths Object

Page 98: Basic JavaScript Tutorial

Exercise 1: Display messages with alertAn alert box is often used if you want to make sure information comes through to theuser. 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 windowself.alert('message') // reference to current windowtop.alert('message') // top-level framesetparent.alert('message') // parent frame in a frameset

Examples:alert('I am an alert box!');

Page 99: Basic JavaScript Tutorial

Exercise 2: Math Rules: Order of operation math rules

The simplest way I can explain how javascript handles mathematics is byusing the popular bodmas rules.

B -Brackets firstO - 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 meansthat operators higher takes precedence (just like bodmas).https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Page 100: Basic JavaScript Tutorial

Exercise 3: The Javascript Maths ObjectMath is a built-in object that has properties and methods for mathematical constantsand functions. Not a function object.You can use it to perform other tasks such as get the value of PI (as in length of acycle 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 64document.write(Math.sqrt(64)); //answer 8

Example 3: Calculate the sine of 90document.write(Math.sin(90));

Example 4: Calculate the cosine of 90document.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

Page 101: Basic JavaScript Tutorial

Working With Variables, Strings & PromptDialog

Variables: Store data with variablesPrompt Box: Ask questions with promptAdding Strings: Joining strings and numbers with +

Page 102: Basic JavaScript Tutorial

Exercise 1: Store Data With VariablesI 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 VariablesAs with algebra, JavaScript variables can be used to hold values (x = 5) orexpressions (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,enumexport,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

Page 103: Basic JavaScript Tutorial

Exercise 2: Prompt Box: Ask questions with promptThe Window.prompt() displays a dialog with an optional messageprompting 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 beomitted 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 isan optional parameter. Note that in Internet Explorer 7 and 8, if you do not providethis 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 shallbe treated in a later chapter.var sign = prompt('What is your sign?');if (sign == 'scorpio') {alert('Wow! I am a Scorpio too!');}

Page 104: Basic JavaScript Tutorial

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

Page 105: Basic JavaScript Tutorial

If Statements, Boolean values & Null valuesCheck user responses with if statementsBoolean values: true & falseNull value: The special value null

Page 106: Basic JavaScript Tutorial

Exercise 1: Check user responses with if statementsOne of the most important features of a computer language is the capability to testand compare values. This allows your scripts to behave differently based on thevalues of variables, or based on input from the user.

The if statement is the main conditional statement in JavaScript. This statementmeans much the same in JavaScript as it does in English—for example, here is atypical 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 anexample 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 alertmessage. Otherwise, it does nothing.

If you use an if statement like the preceding example, you can use a single statementas the action. You can also use multiple statements for the action by enclosing themin 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, itdisplays a message and sets a back to 0.

Conditional OperatorsWhile the action part of an if statement can include any of the JavaScript statementsyou've already learned (and any others, for that matter), the condition part of thestatement uses its own syntax. This is called a conditional expression.

Page 107: Basic JavaScript Tutorial

A conditional expression includes two values to be compared (in the precedingexample, the values were a and 1). These values can be variables, constants, or evenexpressions in themselves.

Note:Either side of the conditional expression can be a variable, a constant, or anexpression. You can compare a variable and a value, or compare two variables. (Youcan compare two constants, but there's usually no reason to.)

Between the two values to be compared is a conditional operator. This operator tellsJavaScript how to compare the two values. For instance, the == operator is used totest whether the two values are equal. A variety of conditional operators areavailable:

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 herevar x = 5;if(x == 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 3b: Note that x is a string herevar 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 andvariable types, a different result will be seen

Example 4a: Note that x is an integer here

Page 108: Basic JavaScript Tutorial

var x = 5;if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 4b: Note that x is a string herevar x = '5';if(x === 5) {alert('x is equal to 5');} else {alert('Not equal');}

Example 5: using comparisonvar 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 assigninga value to a variable, and == when comparing values. Confusing these two is one ofthe most common mistakes in JavaScript programming.

Page 109: Basic JavaScript Tutorial

Exercise 2: Boolean values: true & falseBoolean 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 inif() statements.

In Boolean logic, a statement can have two values, true or false. When using Booleanlogic in philosophy, the statement can be a sentence, likeIt rains today.

In more down-to-earth applications like JavaScript, a statement is something likex == 4

Both statements can be either true or false. When writing a program it is oftennecessary 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 awhole 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 aregetting 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 aregetting wet is true OR if both statements are true.

This is also very useful when writing programs. For instance, suppose you want to dosomething 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.

Page 110: Basic JavaScript Tutorial

Exercise 3: Null value: The special value nullJavascript 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

Page 111: Basic JavaScript Tutorial

Confirm Command, Combining conditions &While loop

The confirm commandCombining conditions with && and ||While loop: Repeat code with while loops

Page 112: Basic JavaScript Tutorial

Exercise 1: The confirm commandThis is used to confirm a user about certain action, and decide between two choicesdepending 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, andFALSE when cancel is clicked.Example:var x=window.confirm('Are you sure you are ok?');if (x)window.alert('Good!');elsewindow.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');}

Page 113: Basic JavaScript Tutorial

Exercise 2: Combining conditions with && and ||We have looked at the comparison operators above (>,<,==,=== etc), now, wewant 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 trueif ((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 trueif ((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 andfalse 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 resultif ((20 != 20) && (50 != 200)) {alert('this block will not run because 20 is 20 and cannot be anything else');}

Javascript Conditional OperatorJavaScript also contains a conditional operator that assigns a value to a variablebased on some condition.Syntax: variablename = (condition) ? value1:value2

Consider this statement:

Page 114: Basic JavaScript Tutorial

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 thesame result:

var age=15;var voteable = (age < 18) ? 'Too young':'Old enough';alert(voteable);

Page 115: Basic JavaScript Tutorial

Exercise 3: While loop: Repeat code with while loopsLoops 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 sowe end this tutorial.

NEXT: JavaScript Functions, Arrays & Dates

< If Statements, Boolean values & Null values

Page 116: Basic JavaScript Tutorial

JavaScript Functions, Arrays & DatesString functions in JavaScriptJavaScript FunctionsWorking With ArraysWorking With Dates

Page 117: Basic JavaScript Tutorial

Exercise 1: String functions in JavaScriptJavaScript 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” withinthe string.

var message="jquery4u"; alert(message.charAt(1)); //alerts "q"

3. concat(v1, v2,…) Combines one or more strings (arguments v1, v2 etc) into theexisting 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 specifiedsequence of Unicode values (arguments c1, c2 etc). Method of String object, notString instance. For example: String.fromCharCode().

alert(String.fromCharCode(97,98,99,120,121,122)); //output: abcxyzalert(String.fromCharCode(72,69,76,76,79)); //output: HELLO

5. indexOf(substr, [start]) Searches and (if found) returns the index number of thesearched character or substring within the string. If not found, -1 is returned. “Start” isan optional argument specifying the position within string to begin the search. Defaultis 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 ofthe searched character or substring within the string. Searches the string from end tobeginning. If not found, -1 is returned. “Start” is an optional argument specifying theposition within string to begin the search. Default is string.length-1.

Page 118: Basic JavaScript Tutorial

//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 regularexpression. It returns an array of information or null if no match is found.

//match(regexp) //select integers onlyvar 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 regularexpression (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.

Page 119: Basic JavaScript Tutorial

//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 ifnone 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 specifieddelimiter, and returns an array containing each element. The optional “limit” is aninteger 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 ifomitted, 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

Page 120: Basic JavaScript Tutorial

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 tolowercase.

//toLowerCase()var myString = 'JAVASCRIPT ROX';myString = myString.toLowerCase();alert(myString)//output: javascript rox

15. toUpperCase() Returns the string with all of its characters converted touppercase.

//toUpperCase()var myString = 'javascript rox';myString = myString.toUpperCase();alert(myString)//output: JAVASCRIPT ROX

Page 121: Basic JavaScript Tutorial

Exercise 2: Creating JavaScript FunctionsJavaScript also allows us to create custom functions to solve our everydayfunctionalities. 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 inthe two examples below, you will not get any result because the functions were notcalled 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 functionsvar 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 functionthat will alert the first and last name of a person.

Example 5:

Page 122: Basic JavaScript Tutorial

function myname(first,last) {alert('Your full name is '+first+' '+last);}myname('Tony', 'Olawale');

Example 6: A function can also return a resultfunction myname(first,last) {var r='Your full name is '+first+' '+last;return r;}var fullname=myname('Tony', 'Olawale');alert(fullname);

Page 123: Basic JavaScript Tutorial

Exercise 3: Working With ArraysAn Array is an enumerated list of variables. It's a programming construct that allowsprogrammers 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, allowingfor 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 ArrayMost 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 wantto 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 willautomatically increase the size of the Array as needed, as you add items into theArray. Creating an Array with brackets instead of with thenew constructor avoids a bit

Page 124: Basic JavaScript Tutorial

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 elements. 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 addmore than one item then badArray would be initialized correctly since Javascript wouldthen be smart enough to know that you were initializing the array instead of statinghow many elements you wanted to add.

Since the new constructor is not necessary with Arrays and there's a slight chance ofunintended results by using the new constructor, it's recommended you not use newArray() to create an Array.

Initializing An ArrayYou 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 output: 4>undefined document.writeln('5>'+myArray[5]+'<BR>'); // Will output: 5>March

Storing Data In An ArrayAn array can store anything you can assign to a variable: booleans, numbers, strings,functions, objects, other Arrays, even regular expressions…

Page 125: Basic JavaScript Tutorial

var myArray = [ 3, 'hello!', function() {return 5}, {'color':'blue', 'budget':25}, /[ell]/i ]; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>3 document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>hello! document.writeln('2>'+myArray[2]()+'<BR>'); // Will output: 2>5 document.writeln('3>'+myArray[3].color+'<BR>'); // Will output: 3>blue document.writeln('3>'+myArray[3].budget+'<BR>'); // Will output: 3>25 document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true

Multi-Dimensional ArraysSince an Array can store other Arrays you can get the benefit of multi-dimensionarrays.

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 firstelement in the array y. If we ask for the value of y[0] it will return the contents of x asa 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 ReferenceArrays are passed to functions by reference, or as a pointer to the original. This meansanything 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]); // Will output: changed

Javascript Arrays Are Assigned By ReferenceAssigning an Array to a new variable creates a pointer to the original Array. Forinstance…

Page 126: Basic JavaScript Tutorial

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]; var newArray= myArray; newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: changed

Passing Arrays As ValuesTo 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.slice(); newArray[1] = 'changed'; document.writeln(myArray[1]); // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'; } passedByReference(myArray.slice()); document.writeln(myArray[1]); // Will output: one

Array.lengthEvery Array has a length property. This always contains the number of elements in thearray. Since Arrays always start at zero, the length property is convenient for loopssince it will always be one greater than the actual index. For instance if the Array has10 elements then the indexes will be 0-9, so as long as our counter is less than theArray.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 itemsare undefined the length property will still count them because it's always one higherthan 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>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 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 100elements in an array and set the length to 50, Javascript will truncate the last 50elements from the array (effectively deleting them). If you have 10 elements in anarray and set Array.length to 100 then the length of the array will be expanded to100, creating 90 undefined elements after the original 10 items.

Javascript Does Not Support Associative ArraysAn associative array is an array which uses a string instead of a number as an index.

Page 127: Basic JavaScript Tutorial

var normalArray = []; normalArray[1] = 'This is an enumerated array'; alert(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… Allarrays in Javascript are objects and Javascript's object syntax gives a basic emulationof an associative Array. For this reason the example code above will actually work. Bewarned 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 andmethods, just like .length, .sort(), .splice(), and all the other built-in properties andmethods.

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) { document.writeln(i+':'+associativeArray[i]+', '); // outputs: one:First, two:Second, three:Third };

In the above example, associativeArray.length will be zero because we didn't actuallyput anything into the Array, we put it into associativeArray'sobject. associativeArray[0] will be undefined.

The loop in the above example will also pick up any methods, properties, andprototypes which have been added to the array and not just your data. A lot ofproblems people have with the Prototype library is that their associative arrays breakbecause Prototype adds a few useful Prototype functions to the Array object and for iin x loops pick up those additional methods. That's the pitfal of using Array/objects asa poor man's associative array.

As a final example, the previous code will work regardless of whether you defineassociativeArray 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.

Page 128: Basic JavaScript Tutorial

Exercise 4: Working With DatesOf all the core Javascript objects, I find Dates to be the most fascinating. Once youlearn a few small tricks everything about Javascript Dates just seem to fall into placeand you find that there's really nothing at all that you can't do with them, quickly, andeasily.

This reference will cover the Javascript Date Object, how it stores Dates, how you canmanipulate them, create calendars, countdown timers, prototype them to add yourown functionality, as well as provide a complete method reference.

Julian DatesJulian Dates are a method of referencing time and dates based on how much time haspassed since an arbitrary number in the past. For instance, 215 days have presentlypassed this year. If we know that January 1 begins on a Wednesday , then we knowthat day 2 represents a Thursday in January. If we know there are 31 days in Januarythen we know that day 32 represents the first of February and we can figure out thatFebruary 1st fell on a Saturday.

Javascript (and most languages) handle dates exactly as described above, only inmuch grander fashion. Theepoch or starting point of Javascript's date system isn'tJanuary 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and itdoesn't count just days! No Javascript counts the number of milliseconds that havepassed 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 numbersindicate dates after 1970 and negative numbers indicate dates prior to 1970. Forinstance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascriptcounts in milliseconds and there are 1000 milliseconds in a single second so -1000represents 1 second.

By a great coincidence Unix also uses January 1, 1970 as it's epoch date which meansa timestamp in Javascript will match a timestamp on your server as long as you takesome 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 severalways to create and set Dates. The one you're most likely to use is simply to specify

Page 129: Basic JavaScript Tutorial

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 thebrowser'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 couldalso 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 thedate printed are unlikely to match. The created date is actually 2:54:16 in the GMTtimezone, however when we printed the date out, since we didn't specify anythingspecial, the date was printed in the Browser's time zone so the browser did a littleconversion for us to ensure the time we printed was the ACTUAL time relative to thebrowser.

That's a little confusing so let's try for something different. Every New Years Eve, thecity of New York holds a big celebration and the ball is dropped at precisely midnightin 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 atime 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 cansee what time the ball will be dropping in your timezone! (of course people in theeastern 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 Dateobject. 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 objectwill try to parse it (see previous section), if it's a long integer it will try to use it as ajulian number. If there are more than one argument it will build the date from yoursupplied arguments.

Page 130: Basic JavaScript Tutorial

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 monthsgo 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 NumbersWorking with Julian Dates requires division and modulus. Division will discard theportion of the date you no longer need and modulus (which is the remainder ofdivision) will return the portion of the date you are looking for.

Most people don't need milliseconds when doing date calculation, so we just dividethe Julian Date Number by 1,000. So if we have a Julian Day Number of1,177,303,066,354 then dividing this by 1,000 will give us a day number of1,177,303,066 -- a number which no longer holds information about the millisecondsin the date.

To get the number of seconds this represents, we take the modulus of 60 becausethere 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 dateby 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 findout how many minutes the number represents by taking the modulus of 60 since thereare 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. Whatremains are hours and days. We can get the hours by taking the modulus of 24 sincethere are 24 hours in a day. Then divide the daynumber by 24 to discard the hours,leaving only the number of days.

Page 131: Basic JavaScript Tutorial

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 JavascriptIn 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 ofmilliseconds that had elapsed since January 1, 1970. But we could just as easily haveused 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. Bysubtracting now from newYear we get an integer which represents the differencebetween the two dates, specifically: 12,914,813,502.

We can use division and modulus to extract the time from this number just like we didin the previous section only now we're computing the difference between now and thenew year instead of a date and January 1, 1970.

This article is generating now and newYear in real-time so the values below are theactual 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 012015 00:00:00 GMT+0100 (W. Central Africa Standard Time).

Page 132: Basic JavaScript Tutorial

Making a TimerIn the example above now is equal to the instant it is created while newYear is aconstant value, always equal to January 1 of next year. So it's actually very easy tomake a timer. All we have to do is turn the code above into a function, set up asetTimeout command, and create a html division somewhere on the page to hold ourtimer. 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>

Page 133: Basic JavaScript Tutorial

When the function is called (every second), now is always set to the current, everadvancing date, while the newYear always remains a constant. So the function worksto 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 andthe new year is in daylight savings time! If this is the case, once everyone falls backthe timer will again be in sync with your expectations!

Making A ClockMaking a clock is very similar to making a countdown timer. All we have to do is tocreate 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 MonthJavascript has a little quirk where a date of zero will set the date to be the last day ofthe previous month. Likewise is there are 30 days in a month and you set a date of 31it will be the 1st day of the next month, a date of 40 would be the 10th day of thenext month. This can lead to some very weird funkiness if you're not careful but wecan definitely exploit this for a useful prototype which will give us the number of daysin 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!):

Page 134: Basic JavaScript Tutorial

Getting The Name Of The Day And MonthWhile the Javascript Date Object has many useful features, one glaring oversight isthat when you ask it for the day or month it will return only the numericalrepresentation. This is easy enough to fix with prototypes however.

Date.prototype.getDayName = function(shortName) { var Days = ['Sunday', 'Monday', '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', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][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 argumentto getDayName. As long as the argument isn't false, null or any other falsey value thename will be shortened to its three letter equivalent.

var d = new Date(); day = d.getDayName(true);

< Confirm Command, Combining conditions & While loop