Put this anywhere in the head or body:
<script type="text/javascript">
// your javascript here
</script>
Here's how to add content to a page using JavaScript:
document.write("hello!");
JavaScript is a loosely typed language, so here's all you need to do to create a variable:
var varName = "value"; // if you don't declare a variable like this, JS will implicitly declare it for you.
///then you can use it:
varName++;
for (var i = 1; i < 10; i++)
{
}
for (var i in myArray)
{
//do something to each element of myArray
}
var footer = document.getElementById("footer");
// do something with footer
footer.innerHTML = "test"; // now the footer element just contains "test"
var footer = document.getElementById("footer");
footer.innerHTML = "hello!";
function test(arg1, arg2) {
}
In Javascript, all parameters are optional, so your function can be called in these three ways:
test();
test(0);
test(0,1);
Here's the customary way of providing defaults in case some parameters are skipped:
arg1 = arg1 || 0; // default is 0.
arg2 = arg2 || 4; // default is 4.
Variable-length arguments
Each function is passed an arguments array containing all the arguments. You can use this to write functions with arguments of variable lengths:
// this function will add together all the numbers you give it and return the result
function add()
{
adder = 0;
for (x = 0;x
adder+=arguments[x]
}
return adder;
}
Passing functions as parameters
This is perfectly legal:
function add(a,b)
{
return a + b;
}
function operate(operator,a,b)
{
operator(a,b);
}
operate(add,a,b);
Function Properties
In JS, all variables are global. If you're using a variable in a function and you don't want to clutter the namespace, you can define it as a property on the function:
test.counter = 0;
function test()
{
document.write(test.counter++); // notice we write test.counter and not this.counter.
}
If you create a constructor, the function properties of the constructor will be the Class variables for whatever object it's constructing. For example:
Rectangle.foo = 50; // Class variable
function Rectangle(w)
{
this.width = w;
this.height = Rectangle.foo; // we're using the class variable here
}
var r = new Rectangle(25); // a Rectangle with a width of 25 and a height of 50
Javascript URLs are sort of like Perl one-liners. Just put some javascript code into the location field of yur web browser, preceded by a "javascript:". Then hit enter. Your browser will show you the result of your code in a new page. For example:
// put this in your location field
javascript:2+5
If a number goes out of range, JavaScript assigns it the special value of 'Infinity'.
If a numerical value yields an error or an undefined result, JavaScript assigns it the value NaN.
NaN is not equal to any number, even itself. To check it a number is NaN, use the special function
isNaN()
To check for infinity, use the special function
isFinite()
myStr.length
myStr.charAt(0); // gets the first character of myStr
myStr = "aditya";
var sub = myStr.substring(1,4); // sub is now "dit"
myStr = "aditya";
var i = myStr.indexOf('d'); // returns 1
// to get the first occurrence of a letter
var j = myStr.indexOf('a'); // returns 0
// to get the last occurrence of a letter
var k = myStr.lastIndexOf('a'); // returns 5
myNum = 200;
// any of these will work
myStr = myNum + "";
myStr = String(myNum);
myStr = myNum.toString();
myNum = 17;
myBin = myNum.toString(2); //Binary version of myNum
myHex = "0x" + myNum.toString(16); //Hex version of myNum
myOct = "0" + myNum.toString(8); //Octal version of myNum
Objects in JavaScript are similar to associative arrays.Objects in JavaScript are similar to associative arrays.
var watterson = new Object(); // new object made
watterson.comic = "calvin and hobbes"; // new property added
watterson["comic" = "calvin and hobbes"; // another way to write it
document.write(watterson.comic); // outputs "calvin and hobbes"
//another way to make objects
var watterson = {
"name":"Bill Watterson",
"fame":"Calvin and Hobbes"
}
//check if a property exists
if (fame in watterson)
{
alert(watterson.fame);
}
Methods
function addToFame()
{
this.fame+=" is awesome";
}
watterson.add = addToFame; // notice lack of parens after 'addToFame'
watterson.add(); // now watterson.fame is set to "Calvin and Hobbes is awesome";
// Another way to do the same thing without making addToFame a method of watterson:
addToFame.call(watterson);
// if it had parameters, we'd call it like this:
addToFame.call(watterson,param1,param2);
// Initializing
var a = new Array();
var a = new Array(10); // creates an array with ten undefined elements
var a = [10,"aditya",{x:1,y:2}]
// Length
a.length
// Length is a read/write value, so you can do this too:
a.length = 2; // if the array was bigger than two, some values have been truncated.
// Shift Left
a = 11; // in binary
b = a << 1; // shifts the numbers in a to the left by 1
// now b = 110.
So shift left is like multiplying by 2, because in the above example a = 3 and b = 6.
// Shift Right
b = 110; // in binary
a = a >> 1; // shifts the numbers in b to the right by 1
// now a = 11.
So shift right is like dividing by 2.
Sometimes also known as the ternary operator. It is used like this:
[expression] ? [do this if true] : [do this if false]
// an example
greeting = "hello ";
username!=null? greeting+=username : greeting+="there"
// in the above code, if username is set, greeting is set to "hello " + the username, otherwise the greeting is "hello there".
t = 1;
a = typeof t; // a is now set to 'number'
To exit a loop, use:
break;
To go to the next iteration in a loop, use:
continue;
If you have more than one loop and you want to specify which one to break or continue, ass a label to the loop like this:
myLabel: // this is the label of the loop
while(1==0) // some loop
{
break myLabel; // specify label in break
}
if (1==0) throw new Error("that's impossible!");
try
{
}catch (e)
{
}
finally
{
}
Instead of writing this:
frames[1].document.forms[0].address.value = "";
frames[1].document.forms[0].name.value = "";
frames[1].document.forms[0].email.value = "";
You can write this instead:
with (frames[1].document.forms[0])
{
address.value = = "";
name.value = = "";
email.value = = "";
}
You can't create true multidimensional arrays, but since you can put anything you want in an array, you can make an array of arrays, which is as good as a true two-dimensional array.
var myArray = [[1,0,0,0],
[1,1,2,3],
[2,1,4,5]];
myArray[0][1] = 2; // the format is [row][column].
Join
var a = [1,2,3];
var s = a.join(); // s is now "1,2,3"
var t = a.join("/"); // s is now "1/2/3"
Reverse
var a = [1,2,3];
a.reverse(); // a is now [3,2,1]
Sort
var a = [1,2,3];
a.sort(); // a is now sorted in alphabetical order (even though it has numbers)
// here's how to sort it numerically
a.sort( function (a,b) { return a-b; });
// same as perl, you can specify a sort function.
// If a should appear before b, the function returns a number less than 0.
// If b should appear before a, the function returns a number greater than 0.
// If their order is irrelevant b/c they're equal, the function should return 0.
Concat
var a = [1,2,3];
var b = [4,5,6];
var c = a.concat(b); // c = [1,2,3,4,5,6]
Slice
The first number is the starting index, the second number is the ending index. The ending is non-inclusive.
var a = [1,2,3];
var b = a.slice(0,1); // b = [1]
var c = a.slice(1,3); // c = [1,2,3]
Splice
Same as slice, but it removes the elements specified from the array instead of returning them.
Push, Pop, Shift, Unshift
They're all the same as Perl.
var a = [1,2,3];
a.push(50); // a = [1,2,3,50]
a.pop(); // a = [1,2,3]
a.unshift(20); // a = [20,1,2,3]
a.shift(); // a = [1,2,3]
Split
Given a string, splits it on a given string or regex into an array. For example:
var s = "1,2,3,4,5";
var a = s.split(","); // a is now [1,2,3,4,5]
var b = s.split(/,/); // same thing
Constructors
function Rectangle(w,h)
{
this.width = w;
this.height = h;
}
Methods
Rectangle.prototype.test = function()
{
//write code for the method here
}
var r = new Rectangle();
r.test();
These are some methods you might want to define for your object.
toString()
This method is called when a string representation of your object is needed. Just add a new toString() method to your object, and that method will be called instead of the default toString method.
valueOf()
Same as toString(), valueOf() is called when JS needs to convert your object into anything except a string — a number, for example.
Suppose you have this class:
function Rectangle(w,h)
{
this.width = w;
this.height = h;
}
And you want to make a class Square that inherits from Rectangle. First, we use constructor chaining to call the Rectangle constructor from within the Square constructor:
function Square(w,h)
{
Rectangle.call(this,w,h);
// now we can add any new properties if we want
this.x = 0;
this.y = 0;
}
Next we need to set Square's prototype to Rectangle (it is Object by default):
Square.prototype = new Rectangle();
Since the prototype was created with a Rectangle constructor, it has a constructor property that refers to that constructor. But we want it to have a Square constructor instead, so:
Square.prototype.constructor = Square;
And finally, we're done inheriting. Square now inherits from Rectangle.
Invoking Overridden Methods
If both Square and Rectangle have their own area method, here's how you define that you want to use Rectangle's area method from inside a function in Square:
Rectangle.prototype.area.call(this);
The best way to avoid global variables in JavaScript is to attach them to an object instead.
For example, instead of this:
global1 = 10;
global2 = 20;
global3 = 30;
global4 = 40;
Do this:
var myClass = new Object();
myClass.global1 = 10;
myClass.global2 = 20;
myClass.global3 = 30;
myClass.global4 = 40;
This is especially important if you're building a reusable module that will be distributed and used by many people. Cluttering the namespace can lead to some hard-to-catch errors. If you attach variables to an object, you're only introducing one variable in the global namespace.
Create a Regular Expression
var myExp = /.*/; // match anything
JavaScript borrows heavily from Perl for regular expressions, so feel right at home.
JS also supports the g, i and m flags for regular expressions.
Using Regular Expressions
var myExp = /i/; // match anything
var myStr = "perlish";
// SEARCH
myStr.search(myExp); // returns the character position of the start of the first matching substring or -1 if there was no match
myStr.search(/i/); // another way to write it
// MATCH
myStr.match(/i/); // returns an array containing the results of the match. In this case, returns ["i"]. If the global (g) flag isn't set, the array returned contains the match as the first element, and any variables such as $1, $2, etc as subsequent elements.
// REPLACE
myStr.replace(/perl/i,"JS"); // myStr is now "JSish"
// JS also saves expressions in $1, $2 etc, same as Perl
// the second argument doesn't need to be a string...it can be a function that dynamically computes the string.