XML Applications

Toggle navigation
TUTORIAL HOME
XML Applications
❮ Previous Next ❯
This chapter demonstrates some HTML applications using XML, HTTP, DOM, and JavaScript.

The XML Document Used
In this chapter we will use the XML file called “cd_catalog.xml”.

Display XML Data in an HTML Table
This example loops through each element, and displays the values of the and the elements in an HTML table:

Example

table, th, td {
  border: 1px solid black;
  border-collapse:collapse;
}
th, td {
  padding: 5px;
}

function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myFunction(this);
    }
  };
  xmlhttp.open(“GET”, “cd_catalog.xml”, true);
  xmlhttp.send();
}
function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table=”

Artist Title

“;
  var x = xmlDoc.getElementsByTagName(“CD”);
  for (i = 0; i <x.length; i++) {
    table += “

” +
    x[i].getElementsByTagName(“ARTIST”)[0].childNodes[0].nodeValue +
    “ ” +
    x[i].getElementsByTagName(“TITLE”)[0].childNodes[0].nodeValue +
    “

“;
  }
  document.getElementById(“demo”).innerHTML = table;
}

»
For more information about using JavaScript and the XML DOM, go to DOM Intro.

Display the First CD in an HTML div Element
This example uses a function to display the first CD element in an HTML element with id=”showCD”:

Example
displayCD(0);

function displayCD(i) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myFunction(this, i);
        }
    };
    xmlhttp.open(“GET”, “cd_catalog.xml”, true);
    xmlhttp.send();
}

function myFunction(xml, i) {
    var xmlDoc = xml.responseXML;
    x = xmlDoc.getElementsByTagName(“CD”);
    document.getElementById(“showCD”).innerHTML =
    “Artist: ” +
    x[i].getElementsByTagName(“ARTIST”)[0].childNodes[0].nodeValue +
    “
Title: ” +
    x[i].getElementsByTagName(“TITLE”)[0].childNodes[0].nodeValue +
    “
Year: ” +
    x[i].getElementsByTagName(“YEAR”)[0].childNodes[0].nodeValue;
}
»
Navigate Between the CDs
To navigate between the CDs, in the example above, add a next() and previous() function:

Example
function next() {
  // display the next CD, unless you are on the last CD
  if (i < x.length-1) {
    i++;
    displayCD(i);
  }
}

function previous() {
  // display the previous CD, unless you are on the first CD
  if (i > 0) {
  i–;
  displayCD(i);
  }
}
»
Show Album Information When Clicking On a CD
The last example shows how you can show album information when the user clicks on a CD:

.

❮ Previous Next ❯

JavaScript Number Methods

TUTORIAL HOME
JavaScript Number Methods
❮ Previous Next ❯
Number methods help you work with numbers.

Number Methods and Properties
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

The toString() Method
toString() returns a number as a string.

All number methods can be used on any type of numbers (literals, variables, or expressions):

Example
var x = 123;
x.toString();            // returns 123 from variable x
(123).toString();        // returns 123 from literal 123
(100 + 23).toString();   // returns 123 from expression 100 + 23
»
The toExponential() Method
toExponential() returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of characters behind the decimal point:

Example
var x = 9.656;
x.toExponential(2);     // returns 9.66e+0
x.toExponential(4);     // returns 9.6560e+0
x.toExponential(6);     // returns 9.656000e+0
Try it yourself »
The parameter is optional. If you don’t specify it, JavaScript will not round the number.

The toFixed() Method
toFixed() returns a string, with the number written with a specified number of decimals:

Example
var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000
Try it yourself »
toFixed(2) is perfect for working with money.

The toPrecision() Method
toPrecision() returns a string, with a number written with a specified length:

Example
var x = 9.656;
x.toPrecision();        // returns 9.656
x.toPrecision(2);       // returns 9.7
x.toPrecision(4);       // returns 9.656
x.toPrecision(6);       // returns 9.65600
»
The valueOf() Method
valueOf() returns a number as a number.

Example
var x = 123;
x.valueOf();            // returns 123 from variable x
(123).valueOf();        // returns 123 from literal 123
(100 + 23).valueOf();   // returns 123 from expression 100 + 23
»
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.

There is no reason to use it in your code.

All JavaScript data types have a valueOf() and a toString() method.

Converting Variables to Numbers
There are 3 JavaScript methods that can be used to convert variables to numbers:

The Number() method
The parseInt() method
The parseFloat() method
These methods are not number methods, but global JavaScript methods.

Global Methods
JavaScript global methods can be used on all JavaScript data types.

These are the most relevant methods, when working with numbers:

Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer
The Number() Method
Number() can be used to convert JavaScript variables to numbers:

Example
x = true;
Number(x);        // returns 1
x = false;    
Number(x);        // returns 0
x = new Date();
Number(x);        // returns 1404568027739
x = “10”
Number(x);        // returns 10
x = “10 20”
Number(x);        // returns NaN
»
Used on Date(), the Number() method returns the number of milliseconds since 1.1.1970.

The parseInt() Method
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

Example
parseInt(“10”);         // returns 10
parseInt(“10.33”);      // returns 10
parseInt(“10 20 30”);   // returns 10
parseInt(“10 years”);   // returns 10
parseInt(“years 10”);   // returns NaN
Try it yourself »
If the number cannot be converted, NaN (Not a Number) is returned.

The parseFloat() Method
parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

Example
parseFloat(“10”);        // returns 10
parseFloat(“10.33”);     // returns 10.33
parseFloat(“10 20 30”);  // returns 10
parseFloat(“10 years”);  // returns 10
parseFloat(“years 10”);  // returns NaN
Try it yourself »
If the number cannot be converted, NaN (Not a Number) is returned.

Number Properties
Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a “Not-a-Number” value
POSITIVE_INFINITY Represents infinity (returned on overflow)
Example
var x = Number.MAX_VALUE;
Try it yourself »
Number properties belongs to the JavaScript’s number object wrapper called Number.

These properties can only be accessed as Number.MAX_VALUE.

Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

Example
var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined
Try it yourself »
Complete JavaScript Number Reference
For a complete reference, go to our Complete JavaScript Number Reference.

The reference contains descriptions and examples of all Number properties and methods.

❮ Previous Next ❯

JavaScript Math Object

Toggle navigation
TUTORIAL HOME
JavaScript Math Object
❮ Previous Next ❯
The JavaScript Math object allows you to perform mathematical tasks on numbers.

Example
Math.PI;            // returns 3.141592653589793
»
Math.round()
Math.round(x) returns the value of x rounded to its nearest integer:

Example
Math.round(4.7);    // returns 5
Math.round(4.4);    // returns 4
»
Math.pow()
Math.pow(x, y) returns the value of x to the power of y:

Example
Math.pow(8, 2);      // returns 64
»
Math.sqrt()
Math.sqrt(x) returns the square root of x:

Example
Math.sqrt(64);      // returns 8
»
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:

Example
Math.abs(-4.7);     // returns 4.7
»
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:

Example
Math.ceil(4.4);     // returns 5
»
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest integer:

Example
Math.floor(4.7);    // returns 4
»
Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

Example
Math.sin(90 * Math.PI / 180);     // returns 1 (the sine of 90 degrees)
»
Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

Example
Math.cos(0 * Math.PI / 180);     // returns 1 (the cos of 0 degrees)
»
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Example
Math.min(0, 150, 30, 20, -8, -200);  // returns -200
»
Example
Math.max(0, 150, 30, 20, -8, -200);  // returns 150
»
Math.random()
Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive):

Example
Math.random();     // returns a random number
»
You will learn more about Math.random() in the next chapter of this tutorial.

Math Properties (Constants)
JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Example
Math.E        // returns Euler’s number
Math.PI       // returns PI
Math.SQRT2    // returns the square root of 2
Math.SQRT1_2  // returns the square root of 1/2
Math.LN2      // returns the natural logarithm of 2
Math.LN10     // returns the natural logarithm of 10
Math.LOG2E    // returns base 2 logarithm of E
Math.LOG10E   // returns base 10 logarithm of E
»
Math Constructor
Unlike other global objects, the Math object has no constructor. Methods and properties are static.

All methods and properties (constants) can be used without creating a Math object first.

Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns the value of x rounded up to its nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns the value of x rounded down to its nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x, y, z, …, n) Returns the number with the highest value
min(x, y, z, …, n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Returns the value of x rounded to its nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
Complete Math Reference
For a complete reference, go to our complete Math object reference.

The reference contains descriptions and examples of all Math properties and methods.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »

❮ Previous Next ❯

JavaScript Random

JavaScript Random
❮ Previous Next ❯
Math.random()
Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive):

Example
Math.random();              // returns a random number
»
Math.random() always returns a number lower than 1.

JavaScript Random Integers
Math.random() used with Math.floor() can be used to return random integers.

Example
Math.floor(Math.random() * 10);     // returns a number between 0 and 9
»
Example
Math.floor(Math.random() * 11);      // returns a number between 0 and 10
»
Example
Math.floor(Math.random() * 100);     // returns a number between 0 and 99
»
Example
Math.floor(Math.random() * 101);     // returns a number between 0 and 100
»
Example
Math.floor(Math.random() * 10) + 1;  // returns a number between 1 and 10
»
Example
Math.floor(Math.random() * 100) + 1; // returns a number between 1 and 100
»
A Proper Random Function
As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes.

This JavaScript function always returns a random number between min (included) and max (excluded):

Example
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max – min) ) + min;
}
»
This JavaScript function always returns a random number between min and max (both included):

Example
function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max – min + 1) ) + min;
}
»

❮ Previous Next ❯

TUTORIAL HOME JavaScript Dates

Toggle navigation
TUTORIAL HOME
JavaScript Dates
❮ Previous Next ❯
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)

JavaScript Date Formats
A JavaScript date can be written as a string:

Mon Apr 15 2019 16:34:39 GMT+0300 (EAT)

or as a number:

1555335279259

Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

Displaying Dates
In this tutorial we use a script to display dates inside a

element with id=”demo”:

Example

document.getElementById(“demo”).innerHTML = Date();

»
The script above says: assign the value of Date() to the content (innerHTML) of the element with id=”demo”.

You will learn how to display a date, in a more readable format, at the bottom of this page.

Creating Date Objects
The Date object lets us work with dates.

A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

Date objects are created with the new Date() constructor.

There are 4 ways of initiating a date:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Using new Date(), creates a new date object with the current date and time:

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d;

»
Using new Date(date string), creates a new date object from the specified date and time:

Example

var d = new Date(“October 13, 2014 11:13:00”);
document.getElementById(“demo”).innerHTML = d;

»
Valid date strings (date formats) are described in the next chapter.

Using new Date(number), creates a new date object as zero time plus the number.

Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:

Example

var d = new Date(86400000);
document.getElementById(“demo”).innerHTML = d;

»
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.

Using new Date(7 numbers), creates a new date object with the specified date and time:

The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:

Example

var d = new Date(99, 5, 24, 11, 33, 30, 0);
document.getElementById(“demo”).innerHTML = d;

»
Variants of the example above let us omit any of the last 4 parameters:

Example

var d = new Date(99, 5, 24);
document.getElementById(“demo”).innerHTML = d;

»
JavaScript counts months from 0 to 11. January is 0. December is 11.

Date Methods
When a Date object is created, a number of methods allow you to operate on it.

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time.

Date methods are covered in a later chapter.

Displaying Dates
When you display a date object in HTML, it is automatically converted to a string, with the toString() method.

Example

d = new Date();
document.getElementById(“demo”).innerHTML = d;

Is the same as:

d = new Date();
document.getElementById(“demo”).innerHTML = d.toString();

»
The toUTCString() method converts a date to a UTC string (a date display standard).

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d.toUTCString();

»
The toDateString() method converts a date to a more readable format:

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d.toDateString();

»
Date objects are static. The computer time is ticking, but date objects, once created, are not.

Time Zones
When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone.

When getting a date, without specifying the time zone, the result is converted to the browser’s time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

Read more about time zones in the next chapters.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »

❮ Previous Next ❯

TUTORIAL HOME JavaScript Date Formats

Toggle navigation
TUTORIAL HOME
JavaScript Date Formats
❮ Previous Next ❯
JavaScript Date Input
There are generally 4 types of JavaScript date input formats:

Type Example
ISO Date “2015-03-25” (The International Standard)
Short Date “03/25/2015”
Long Date “Mar 25 2015” or “25 Mar 2015”
Full Date “Wednesday March 25 2015”
The ISO format follows a strict standard in JavaScript.

The other formats are not so well defined and might be browser specific.

JavaScript Date Output
Independent of input format, JavaScript will (by default) output dates in full text string format:

Wed Mar 25 2015 03:00:00 GMT+0300 (EAT)
JavaScript ISO Dates
ISO 8601 is the international standard for the representation of dates and times.

The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:

Example (Complete date)
var d = new Date(“2015-03-25”);
»
The computed date will be relative to your time zone.
Depending on your time zone, the result above will vary between March 24 and March 25.

ISO Dates (Year and Month)
ISO dates can be written without specifying the day (YYYY-MM):

Example
var d = new Date(“2015-03”);
»
Time zones will vary the result above between February 28 and March 01.

ISO Dates (Only Year)
ISO dates can be written without month and day (YYYY):

Example
var d = new Date(“2015”);
»
Time zones will vary the result above between December 31 2014 and January 01 2015.

ISO Dates (Date-Time)
ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):

Example
var d = new Date(“2015-03-25T12:00:00Z”);
»
Date and time is separated with a capital T.

UTC time is defined with a capital letter Z.

If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:

Example
var d = new Date(“2015-03-25T12:00:00-06:30”);
»
UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).

Omitting T or Z in a date-time string can give different result in different browser.

Time Zones
When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone.

When getting a date, without specifying the time zone, the result is converted to the browser’s time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

JavaScript Short Dates.
Short dates are written with an “MM/DD/YYYY” syntax like this:

Example
var d = new Date(“03/25/2015”);
»
WARNINGS !
In some browsers, months or days with no leading zeroes may produce an error:

var d = new Date(“2015-3-25”);
The behavior of “YYYY/MM/DD” is undefined.
Some browsers will try to guess the format. Some will return NaN.

var d = new Date(“2015/03/25”);
The behavior of  “DD-MM-YYYY” is also undefined.
Some browsers will try to guess the format. Some will return NaN.

var d = new Date(“25-03-2015”);
JavaScript Long Dates.
Long dates are most often written with a “MMM DD YYYY” syntax like this:

Example
var d = new Date(“Mar 25 2015”);
»
Month and day can be in any order:

Example
var d = new Date(“25 Mar 2015”);
»
And, month can be written in full (January), or abbreviated (Jan):

Example
var d = new Date(“January 25 2015”);
»
Example
var d = new Date(“Jan 25 2015”);
»
Commas are ignored. Names are case insensitive:

Example
var d = new Date(“JANUARY, 25, 2015”);
»
JavaScript Full Date
JavaScript will accept date strings in “full JavaScript format”:

Example
var d = new Date(“Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard Time)”);
»
JavaScript will ignore errors both in the day name and in the time parentheses:

Example
var d = new Date(“Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo Time)”);
»

❮ Previous Next ❯

JavaScript Date Methods

Toggle navigation
TUTORIAL HOME
JavaScript Date Methods
❮ Previous Next ❯
Date methods let you get and set date values (years, months, days, hours, minutes, seconds, milliseconds)

Date Get Methods
Get methods are used for getting a part of a date. Here are the most common (alphabetically):

Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
The getTime() Method
getTime() returns the number of milliseconds since January 1, 1970:

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d.getTime();

»
The getFullYear() Method
getFullYear() returns the year of a date as a four digit number:

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d.getFullYear();

»
The getDay() Method
getDay() returns the weekday as a number (0-6):

Example

var d = new Date();
document.getElementById(“demo”).innerHTML = d.getDay();

»
In JavaScript, the first day of the week (0) means “Sunday”, even if some countries in the world consider the first day of the week to be “Monday”

You can use an array of names, and getDay() to return the weekday as a name:

Example

var d = new Date();
var days = [“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”];
document.getElementById(“demo”).innerHTML = days[d.getDay()];

»
Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabetically):

Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
The setFullYear() Method
setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:

Example

var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById(“demo”).innerHTML = d;

»
The setDate() Method
setDate() sets the day of the month (1-31):

Example

var d = new Date();
d.setDate(20);
document.getElementById(“demo”).innerHTML = d;

»
The setDate() method can also be used to add days to a date:

Example

var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById(“demo”).innerHTML = d;

»
If adding days, shifts the month or year, the changes are handled automatically by the Date object.

Date Input – Parsing Dates
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.

Date.parse() returns the number of milliseconds between the date and January 1, 1970:

Example

var msec = Date.parse(“March 21, 2012”);
document.getElementById(“demo”).innerHTML = msec;

»
You can then use the number of milliseconds to convert it to a date  object:

Example

var msec = Date.parse(“March 21, 2012”);
var d = new Date(msec);
document.getElementById(“demo”).innerHTML = d;

»
Compare Dates
Dates can easily be compared.

The following example compares today’s date with January 14, 2100:

Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {
    text = “Today is before January 14, 2100.”;
} else {
    text = “Today is after January 14, 2100.”;
}
document.getElementById(“demo”).innerHTML = text;
»
JavaScript counts months from 0 to 11. January is 0. December is 11.

UTC Date Methods
UTC date methods are used for working UTC dates (Universal Time Zone dates):

Method Description
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds
Complete JavaScript Date Reference
For a complete reference, go to our Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and methods.

❮ Previous Next ❯

JavaScript Arrays

JavaScript Arrays
❮ Previous Next ❯
JavaScript arrays are used to store multiple values in a single variable.

Example
var cars = [“Saab”, “Volvo”, “BMW”];
»
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:

var car1 = “Saab”;
var car2 = “Volvo”;
var car3 = “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 solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array_name = [item1, item2, …];      
Example
var cars = [“Saab”, “Volvo”, “BMW”];
»
Spaces and line breaks are not important. A declaration can span multiple lines:

Example
var cars = [
    “Saab”,
    “Volvo”,
    “BMW”
];
»
Putting a comma after the last element (like “BMW”,)  is inconsistent across browsers.

IE 8 and earlier will fail.

Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:

Example
var cars = new Array(“Saab”, “Volvo”, “BMW”);
»
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).

Access the Elements of an Array
You refer to an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];
This statement modifies the first element in cars:

cars[0] = “Opel”;
Example
var cars = [“Saab”, “Volvo”, “BMW”];
document.getElementById(“demo”).innerHTML = cars[0];
»
[0] is the first element in an array. [1] is the second. Array indexes start with 0.

Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:

Example
var cars = [“Saab”, “Volvo”, “BMW”];
document.getElementById(“demo”).innerHTML = cars;
»
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns “object” for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its “elements”. In this example, person[0] returns John:

Array:
var person = [“John”, “Doe”, 46];
»
Objects use names to access its “members”. In this example, person.firstName returns John:

Object:
var person = {firstName:”John”, lastName:”Doe”, age:46};
»
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:

Examples
var x = cars.length;   // The length property returns the number of elements
var y = cars.sort();   // The sort() method sorts arrays
Array methods are covered in the next chapters.

The length Property
The length property of an array returns the length of an array (the number of array elements).

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.length;                       // the length of fruits is 4
»
The length property is always one more than the highest array index.

Looping Array Elements
The best way to loop through an array, is using a “for” loop:

Example
var fruits, text, fLen, i;

fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fLen = fruits.length;
text = “

    “;
    for (i = 0; i < fLen; i++) {
        text += “

  • ” + fruits[i] + “
  • “;
    }
    »
    Adding Array Elements
    The easiest way to add a new element to an array is using the push method:

    Example
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    fruits.push(“Lemon”);                // adds a new element (Lemon) to fruits
    »
    New element can also be added to an array using the length property:

    Example
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    fruits[fruits.length] = “Lemon”;     // adds a new element (Lemon) to fruits
    »
    WARNING !
    Adding elements with high indexes can create undefined “holes” in an array:

    Example
    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
    fruits[6] = “Lemon”;                 // adds a new element (Lemon) to fruits
    »
    Associative Arrays
    Many programming languages support arrays with named indexes.

    Arrays with named indexes are called associative arrays (or hashes).

    JavaScript does not support arrays with named indexes.

    In JavaScript, arrays always use numbered indexes. 

    Example
    var person = [];
    person[0] = “John”;
    person[1] = “Doe”;
    person[2] = 46;
    var x = person.length;         // person.length will return 3
    var y = person[0];             // person[0] will return “John”
    »
    WARNING !!
    If you use a named index, JavaScript will redefine the array to a standard object.
    After that, all array methods and properties will produce incorrect results.

    Example:
    var person = [];
    person[“firstName”] = “John”;
    person[“lastName”] = “Doe”;
    person[“age”] = 46;
    var x = person.length;         // person.length will return 0
    var y = person[0];             // person[0] will return undefined
    »
    The Difference Between Arrays and Objects
    In JavaScript, arrays use numbered indexes. 

    In JavaScript, objects use named indexes.

    Arrays are a special kind of objects, with numbered indexes.

    When to Use Arrays. When to use Objects.
    JavaScript does not support associative arrays.
    You should use objects when you want the element names to be strings (text).
    You should use arrays when you want the element names to be numbers.
    Avoid new Array()
    There is no need to use the JavaScript’s built-in array constructor new Array().

    Use [] instead.

    These two different statements both create a new empty array named points:

    var points = new Array();         // Bad
    var points = [];                  // Good
    These two different statements both create a new array containing 6 numbers:

    var points = new Array(40, 100, 1, 5, 25, 10); // Bad
    var points = [40, 100, 1, 5, 25, 10];          // Good
    »
    The new keyword only complicates the code. It can also produce some unexpected results:

    var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)
    What if I remove one of the elements?

    var points = new Array(40);       // Creates an array with 40 undefined elements !!!!!
    »
    How to Recognize an Array
    A common question is: How do I know if a variable is an array?

    The problem is that the JavaScript operator typeof returns “object”:

    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

    typeof fruits;             // returns object
    »
    The typeof operator returns object because a JavaScript array is an object.

    Solution 1:
    To solve this problem ECMAScript 5 defines a new method Array.isArray():

    Array.isArray(fruits);     // returns true
    »
    The problem with this solution is that ECMAScript 5 is not supported in older browsers.

    Solution 2:
    To solve this problem you can create your own isArray() function:

    function isArray(x) {
        return x.constructor.toString().indexOf(“Array”) > -1;
    }
    »
    The function above always returns true if the argument is an array.

    Or more precisely: it returns true if the object prototype contains the word “Array”.

    Solution 3:
    The instanceof operator returns true if an object is created by a given constructor:

    var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

    fruits instanceof Array     // returns true
    »
    Test Yourself with Exercises!
    Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

    ❮ Previous Next ❯

TUTORIAL HOME JavaScript Array Methods

Toggle navigation
TUTORIAL HOME
JavaScript Array Methods
❮ Previous Next ❯
The strength of JavaScript arrays lies in the array methods.

Converting Arrays to Strings
The JavaScript method toString()  converts an array to a string of (comma separated) array values.

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.toString();
Result
Banana,Orange,Apple,Mango
»
The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
var fruits = [“Banana”, “Orange”,”Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.join(” * “);
Result
Banana * Orange * Apple * Mango
»
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

Popping
The pop() method removes the last element from an array:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.pop();              // Removes the last element (“Mango”) from fruits
»
The pop() method returns the value that was “popped out”:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
var x = fruits.pop();      // the value of x is “Mango”
»
Pushing
The push() method adds a new element to an array (at the end):

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.push(“Kiwi”);       //  Adds a new element (“Kiwi”) to fruits
»
The push() method returns the new array length:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
var x = fruits.push(“Kiwi”);   //  the value of x is 5
»
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.

The shift() method removes the first array element and “shifts” all other elements to a lower index.

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.shift();            // Removes the first element “Banana” from fruits
»
The shift() method returns the string that was “shifted out”:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.shift();             // Returns “Banana”
»
The unshift() method adds a new element to an array (at the beginning), and “unshifts” older elements:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.unshift(“Lemon”);    // Adds a new element “Lemon” to fruits
»
The unshift() method returns the new array length.

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.unshift(“Lemon”);    // Returns 5
»
Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the third …

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits[0] = “Kiwi”;        // Changes the first element of fruits to “Kiwi”
»
The length property provides an easy way to append a new element to an array:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits[fruits.length] = “Kiwi”;          // Appends “Kiwi” to fruit
»
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
delete fruits[0];           // Changes the first element in fruits to undefined
»
Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Splicing an Array
The splice() method can be used to add new items to an array:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.splice(2, 0, “Lemon”, “Kiwi”);
»
The first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters (“Lemon” , “Kiwi”) define the new elements to be added.

Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving “holes” in the array:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.splice(0, 1);        // Removes the first element of fruits
»
The first parameter (0) defines the position where new elements should be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Joining Arrays
The concat() method creates a new array by concatenating two arrays:

Example
var myGirls = [“Cecilie”, “Lone”];
var myBoys = [“Emil”, “Tobias”,”Linus”];
var myChildren = myGirls.concat(myBoys);     // Concatenates (joins) myGirls and myBoys
»
The concat() method can take any number of array arguments:

Example
var arr1 = [“Cecilie”, “Lone”];
var arr2 = [“Emil”, “Tobias”,”Linus”];
var arr3 = [“Robin”, “Morgan”];
var myChildren = arr1.concat(arr2, arr3);     // Concatenates arr1 with arr2 and arr3
»
Slicing an Array
The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1 (“Orange”):

Example
var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
var citrus = fruits.slice(1);
»
The slice() method creates a new array. It does not remove any elements from the source array.

This example slices out a part of an array starting from array element 3 (“Apple”):

Example
var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
var citrus = fruits.slice(3);
»
The slice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to (but not including) the end argument.

Example
var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
var citrus = fruits.slice(1, 3);
»
If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

Example
var fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
var citrus = fruits.slice(2);
»
Automatic toString()
JavaScript will automatically convert an array to a string when a primitive value is expected. These two examples will produce the same result:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.toString();
»
Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits;
»
All JavaScript objects have a toString() method.

Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.

Complete Array Reference
For a complete reference, go to our Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »

❮ Previous Next ❯

JavaScript Sorting Arrays

TUTORIAL HOME
JavaScript Sorting Arrays
❮ Previous Next ❯
The sort() method is one of the strongest array methods.

Sorting an Array
The sort() method sorts an array alphabetically:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.sort();            // Sorts the elements of fruits
»
Reversing an Array
The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.sort();            // Sorts the elements of fruits
fruits.reverse();         // Reverses the order of the elements
»
Numeric Sort
By default, the sort() function sorts values as strings.

This works well for strings (“Apple” comes before “Banana”).

However, if numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”.

Because of this, the sort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a – b});
»
Use the same trick to sort an array descending:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b – a});
»
The Compare Function
The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments:

function(a, b){return a-b}
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

You can use this code snippet to experiment with numerically and alphabetically sorting:

Sort Alphabetically
Sort Numerically

var points = [40, 100, 1, 5, 25, 10];
document.getElementById(“demo”).innerHTML = points;

function myFunction1() {
    points.sort();
    document.getElementById(“demo”).innerHTML = points;
}
function myFunction2() {
    points.sort(function(a, b){return a – b});
    document.getElementById(“demo”).innerHTML = points;
}

»
Sorting an Array in Random Order
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 – Math.random()});
»
Find the Highest (or Lowest) Value
How to find the highest value in an array?

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b – a});
// now points[0] contains the highest value
»
And the lowest:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a – b});
// now points[0] contains the lowest value
»
Sorting Object Arrays
JavaScript arrays often contain objects:

Example
var cars = [
{type:”Volvo”, year:2016},
{type:”Saab”, year:2001},
{type:”BMW”, year:2010}];
Even if objects have properties of different data types, the sort() method can be used to sort the array.

The solution is to write a compare function to compare the property values:

Example
cars.sort(function(a, b){return a.year – b.year});
»
Comparing string properties is a little more complex::

Example
cars.sort(function(a, b){
    var x = a.type.toLowerCase();
    var y = b.type.toLowerCase();
    if (x < y) {return -1;}
    if (x > y) {return 1;}
    return 0;
});
»
Test Yourself with Exercises!
Exercise 1 »

❮ Previous Next ❯