JavaScript and HTML DOM Reference

 

JavaScript Strings

A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

var carname = "Volvo XC60";
var carname = 'Volvo XC60'; 

String indexes are zero-based: The first character is in position 0, the second in 1, and so on.

For a tutorial about Strings, read our JavaScript String Tutorial.

 

String Properties and Methods

Primitive values, like "John Doe", cannot have properties or 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.

 

String Properties

Property

Description

constructor

Returns the string's constructor function

length

Returns the length of a string

prototype

Allows you to add properties and methods to an object

 

String Methods

Method

Description

charAt()

Returns the character at the specified index (position)

charCodeAt()

Returns the Unicode of the character at the specified index

concat()

Joins two or more strings, and returns a new joined strings

fromCharCode()

Converts Unicode values to characters

indexOf()

Returns the position of the first found occurrence of a specified value in a string

lastIndexOf()

Returns the position of the last found occurrence of a specified value in a string

localeCompare()

Compares two strings in the current locale

match()

Searches a string for a match against a regular expression, and returns the matches

replace()

Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced

search()

Searches a string for a specified value, or regular expression, and returns the position of the match

slice()

Extracts a part of a string and returns a new string

split()

Splits a string into an array of substrings

substr()

Extracts the characters from a string, beginning at a specified start position, and through the specified number of character

substring()

Extracts the characters from a string, between two specified indices

toLocaleLowerCase()

Converts a string to lowercase letters, according to the host's locale

toLocaleUpperCase()

Converts a string to uppercase letters, according to the host's locale

toLowerCase()

Converts a string to lowercase letters

toString()

Returns the value of a String object

toUpperCase()

Converts a string to uppercase letters

trim()

Removes whitespace from both ends of a string

valueOf()

Returns the primitive value of a String object

 

String HTML Wrapper Methods

The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

These are not standard methods, and may not work as expected in all browsers.

Method

Description

anchor()

Creates an anchor

big()

Displays a string using a big font

blink()

Displays a blinking string

bold()

Displays a string in bold

fixed()

Displays a string using a fixed-pitch font

fontcolor()

Displays a string using a specified color

fontsize()

Displays a string using a specified size

italics()

Displays a string in italic

link()

Displays a string as a hyperlink

small()

Displays a string using a small font

strike()

Displays a string with a strikethrough

sub()

Displays a string as subscript text

sup()

Displays a string as superscript text

 

 

 

JavaScript Numbers

JavaScript has only one type of number.

Numbers can be written with, or without, decimals:

Example

var x = 3.14;     // A number with decimals
var y = 34;       // A number without decimals

Extra large or extra small numbers can be written with scientific (exponent) notation:

Example

var x = 123e5;    // 12300000
var y = 123e-5;   // 0.00123

For a tutorial about JavaScript numbers, read our JavaScript Number Tutorial.

 

Number Properties

Property

Description

constructor

Returns the function that created JavaScript's Number prototype

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)

prototype

Allows you to add properties and methods to an object

 

Number Methods

Method

Description

toExponential(x)

Converts a number into an exponential notation

toFixed(x)

Formats a number with x numbers of digits after the decimal point

toPrecision(x)

Formats a number to x length

toString()

Converts a number to a string

valueOf()

Returns the primitive value of a number

 

 

 

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5, the table below explains the arithmetic operators: 

Operator

Description

Example

Result in y

Result in x

Try it

+

Addition

x = y + 2

y = 5

x = 7

Try it »

-

Subtraction

x = y - 2

y = 5

x = 3

Try it »

*

Multiplication

x = y * 2

y = 5

x = 10

Try it »

/

Division

x = y / 2

y = 5

x = 2.5

Try it »

%

Modulus (division remainder)

x = y % 2

y = 5

x = 1

Try it »

++

Increment

x = ++y

y = 6

x = 6

Try it »

x = y++

y = 6

x = 5

Try it »

--

Decrement

x = --y

y = 4

x = 4

Try it »

x = y--

y = 4

x = 5

Try it »

For a tutorial about arithmetic operators, read our JavaScript Operators Tutorial

 

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5, the table below explains the assignment operators:

Operator

Example

Same As

Result in x

Try it

=

x = y

x = y

x = 5

Try it »

+=

x += y

x = x + y

x = 15

Try it »

-=

x -= y

x = x - y

x = 5

Try it »

*=

x *= y

x = x * y

x = 50

Try it »

/=

x /= y

x = x / y

x = 2

Try it »

%=

x %= y

x = x % y

x = 0

Try it »

For a tutorial about assignment operators, read our JavaScript Operators Tutorial

 

JavaScript String Operators

The + operator, and the += operator can also be used to concatenate (add) strings.

Given that text1 = "Good ", text2 = "Morning", and text3 = "", the table below explains the operators:

Operator

Example

text1

text2

text3

Try it

+

text3 = text1 + text2 

"Good "

"Morning"

 "Good Morning"

Try it »

+=

text1 += text2 

"Good Morning"

"Morning"

""

Try it »

 

 

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values. 

Given that x=5, the table below explains the comparison operators:

Operator

Description

Comparing

Returns

Try it

==

equal to

x == 8

false

Try it »

x == 5

true

Try it »

===

equal value and equal type

x === "5"

false

Try it »

x === 5

true

Try it »

!=

not equal

x != 8

true

Try it »

!==

not equal value or not equal type

x !== "5"

true

Try it »

x !== 5

false

Try it »

>

greater than

x > 8

false

Try it »

<

less than

x < 8

true

Try it »

>=

greater than or equal to

x >= 8

false

Try it »

<=

less than or equal to

x <= 8

true

Try it »

For a tutorial about comparison operators, read our JavaScript Comparisons Tutorial

 

Conditional Operator

The conditional operator assigns a value to a variable based on a condition.

Syntax

Example

Try it

variablename = (condition) ? value1:value2

voteable = (age < 18) ? "Too young":"Old enough";

Try it »

Example explaied: If the variable "age" is a value below 18, the value of the variable "voteable" will be "Too young", otherwise the value of voteable will be "Old enough".

 

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators: 

Operator

Description

Example

&&

and

(x < 10 && y > 1) is true

||

or

(x == 5 || y == 5) is false

!

not

!(x == y) is true

 

 

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

Operator

Description

Example

Same as

Result

Decimal

&

AND

x = 5 & 1

0101 & 0001

0001

 1

|

OR

x = 5 | 1

0101 | 0001

0101

 5

~

NOT

x = ~ 5

 ~0101

1010

 10

^

XOR

x = 5 ^ 1

0101 ^ 0001

0100

 4

<<

Left shift

x = 5 << 1

0101 << 1

1010

 10

>>

Right shift

x = 5 >> 1

0101 >> 1

0010

2

 

 

JavaScript Statements

In HTML, JavaScript statements are "commands" to the browser.

The purpose, of the statement, is to tell the browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML element identified with id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";


Try it Yourself » 

For a tutorial about Statements, read our JavaScript Statements Tutorial.

 

JavaScript Statement Identifiers

JavaScript statements often start with a statement identifier to identify the JavaScript action to be performed.

Statement identifiers are reserved words and cannot be used as variable names (or any other things).

The following table lists all JavaScript statements:

Statement

Description

break

Exits a switch or a loop

continue

Breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop

debugger

Stops the execution of JavaScript, and calls (if available) the debugging function

do ... while

Executes a block of statements and repeats the block while a condition is true

for

Marks a block of statements to be executed as long as a condition is true

for ... in 

Marks a block of statements to be executed for each element of an object (or array)

function

Declares a function

if ... else ... else if

Marks a block of statements to be executed depending on a condition

return

Stops the execution of a function and returns a value from that function

switch

Marks a block of statements to be executed depending on different cases

throw

Throws (generates) an error

try ... catch ... finally

Marks the block of statements to be executed when an error occurs in a try block, and implements error handling

var

Declares a variable

while

Marks a block of statements to be executed while a condition is true

 

 

Math Object

The Math object allows you to perform mathematical tasks.

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

Syntax

var x = Math.PI;            // Returns PI
var y = Math.sqrt(16);      // Returns the square root of 16 

For a tutorial about the Math object, read our JavaScript Math Tutorial.

 

Math Object Properties

Property

Description

E

Returns Euler's number (approx. 2.718)

LN2

Returns the natural logarithm of 2 (approx. 0.693)

LN10

Returns the natural logarithm of 10 (approx. 2.302)

LOG2E

Returns the base-2 logarithm of E (approx. 1.442)

LOG10E

Returns the base-10 logarithm of E (approx. 0.434)

PI

Returns PI (approx. 3.14)

SQRT1_2

Returns the square root of 1/2 (approx. 0.707)

SQRT2

Returns the square root of 2 (approx. 1.414)

 

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 x, rounded upwards to the nearest integer

cos(x)

Returns the cosine of x (x is in radians)

exp(x)

Returns the value of Ex

floor(x)

Returns x, rounded downwards to the 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)

Rounds x to the 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

 

 

Date Object

The Date object is used to work with dates and times.

Date objects are created with new Date().

There are four ways of instantiating a date:

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); 

For a tutorial about date and times, read our JavaScript Date Tutorial.

 

Date Object Properties

Property

Description

constructor

Returns the function that created the Date object's prototype

prototype

Allows you to add properties and methods to an object

 

Date Object Methods

Method

Description

getDate()

Returns the day of the month (from 1-31)

getDay()

Returns the day of the week (from 0-6)

getFullYear()

Returns the year (four digits)

getHours()

Returns the hour (from 0-23)

getMilliseconds()

Returns the milliseconds (from 0-999)

getMinutes()

Returns the minutes (from 0-59)

getMonth()

Returns the month (from 0-11)

getSeconds()

Returns the seconds (from 0-59)

getTime()

Returns the number of milliseconds since midnight Jan 1, 1970

getTimezoneOffset()

Returns the time difference between UTC time and local time, in minutes

getUTCDate()

Returns the day of the month, according to universal time (from 1-31)

getUTCDay()

Returns the day of the week, according to universal time (from 0-6)

getUTCFullYear()

Returns the year, according to universal time (four digits)

getUTCHours()

Returns the hour, according to universal time (from 0-23)

getUTCMilliseconds()

Returns the milliseconds, according to universal time (from 0-999)

getUTCMinutes()

Returns the minutes, according to universal time (from 0-59)

getUTCMonth()

Returns the month, according to universal time (from 0-11)

getUTCSeconds()

Returns the seconds, according to universal time (from 0-59)

getYear()

Deprecated. Use the getFullYear() method instead

parse()

Parses a date string and returns the number of milliseconds since January 1, 1970

setDate()

Sets the day of the month of a date object

setFullYear()

Sets the year (four digits) of a date object

setHours()

Sets the hour of a date object

setMilliseconds()

Sets the milliseconds of a date object

setMinutes()

Set the minutes of a date object

setMonth()

Sets the month of a date object

setSeconds()

Sets the seconds of a date object

setTime()

Sets a date to a specified number of milliseconds after/before January 1, 1970

setUTCDate()

Sets the day of the month of a date object, according to universal time

setUTCFullYear()

Sets the year of a date object, according to universal time (four digits)

setUTCHours()

Sets the hour of a date object, according to universal time

setUTCMilliseconds()

Sets the milliseconds of a date object, according to universal time

setUTCMinutes()

Set the minutes of a date object, according to universal time

setUTCMonth()

Sets the month of a date object, according to universal time

setUTCSeconds()

Set the seconds of a date object, according to universal time

setYear()

Deprecated. Use the setFullYear() method instead

toDateString()

Converts the date portion of a Date object into a readable string

toGMTString()

Deprecated. Use the toUTCString() method instead

toISOString()

Returns the date as a string, using the ISO standard

toJSON()

Returns the date as a string, formatted as a JSON date