In addition to the mathematical constants that can be accessed from the Math object there are also several methods available.

The following example uses the round() method of the Math object to round a number to the nearest integer:

 document.write(Math.round(4.7));

The code above will result in the following output:
5

The following example uses the random() method of the Math object to return a random number between 0 and 1:

 document.write(Math.random());

The code above can result in the following output:
0.6936874867631697 

The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:

 document.write(Math.floor(Math.random()*11));

The code above can result in the following output:
0


JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.
You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E


The Math object allows you to perform mathematical tasks.

Math Object

The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

 var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.



The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

The Boolean object represents two values: "true" or "false".

The following code creates a Boolean object called myBoolean:

 var myBoolean=new Boolean();

Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false")!
All the following lines of code create Boolean objects with an initial value of false:

 var myBoolean=new Boolean();
var myBoolean=new Boolean(0);
var myBoolean=new Boolean(null);
var myBoolean=new Boolean("");
var myBoolean=new Boolean(false);
var myBoolean=new Boolean(NaN);

And all the following lines of code create Boolean objects with an initial value of true:


var myBoolean=new Boolean(true);
var myBoolean=new Boolean("true");
var myBoolean=new Boolean("false");
var myBoolean=new Boolean("Richard");




To modify a value in an existing array, just add a new value to the array with a specified index number:

 myCars[0]="Opel";

Now, the following code line:

 document.write(myCars[0]);

will result in the following output:
Opel


You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.

The following code line:

 document.write(myCars[0]);

will result in the following output:
 
Saab


The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).

1:

 var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You could also pass an integer argument to control the array's size:

 var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

 var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.


What is an Array?

An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

cars1="Saab";
cars2="Volvo";
cars3="BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The best solution here is to use an array!

An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.


Create a Date Object

The Date object is used to work with dates and times. 
The following code create a Date object called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!

Set Dates

We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();
myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();
myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!

Compare Two Dates

The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2010:

var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();

if (myDate>today)
  {
  alert("Today is before 14th January 2010");
  }
else
  {
  alert("Today is after 14th January 2010");
  }


The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";
document.write(txt.length);

The code above will result in the following output:
12

The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:

var txt="Hello world!";
document.write(txt.toUpperCase());

The code above will result in the following output:
HELLO WORLD!


Methods are the actions that can be performed on objects.
In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:

 <script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
 

The output of the code above will be:
HELLO WORLD!


Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the number of characters in a string:



<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>


The output of the code above will be:
12


JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types.
However, creating your own objects will be explained later, in the Advanced JavaScript section. We will start by looking at the built-in JavaScript objects, and how they are used. The next pages will explain each built-in JavaScript object in detail.
Note that an object is just a special kind of data. An object has properties and methods.


JavaScript is an Object Oriented Programming (OOP) language.
An OOP language allows you to define your own objects and make your own variable types.


Some other important things to know when scripting with JavaScript. 

JavaScript is Case Sensitive

A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar".
JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions.

White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
name="Hege";
name = "Hege";


Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!")
However, you cannot break up a code line like this:
document.write \
("Hello World!");




In JavaScript you can add special characters to a text string by using the backslash sign.

Insert Special Characters

The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
Look at the following JavaScript code:

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
   

In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called
To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:

var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);

JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
Here is another example:

document.write ("You \& I are singing!");

The example above will produce the following output:
You & I are singing!
The table below lists other special characters that can be added to a text string with the backslash sign:
Code Outputs
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed


The throw statement allows you to create an exception.


The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Syntax

throw(exception)
The exception can be a string, integer, Boolean or an object.
Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example

The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:


<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
  {
  if(x>10)
    {
    throw "Err1";
    }
  else if(x<0)
    {
    throw "Err2";
    }
  else if(isNaN(x))
    {
    throw "Err3";
    }
  }
catch(er)
  {
  if(er=="Err1")
    {
    alert("Error! The value is too high");
    }
  if(er=="Err2")
    {
    alert("Error! The value is too low");
    }
  if(er=="Err3")
    {
    alert("Error! The value is not a number");
    }
  }
</script>
</body>
</html>




The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:




<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Click OK to continue viewing this page,\n";
  txt+="or Cancel to return to the home page.\n\n";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>


<body>
<input type="button" value="View message" onclick="message()" />
</body>


</html>


The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

Syntax

try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!


Example

<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.description + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>


<body>
<input type="button" value="View message" onclick="message()" />
</body>


</html>


When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

The try...catch statement allows you to test a block of code for errors.