javascript objects and methods

Objects and methods are predefined functions that perform specific tasks in javascript. They make the codes reusable and shorthand. Lets have a look at few of the most used javascript objects and methods.

Javascript Methods for Arrays

Method Usage
concat() Combines two existing Array objects to one
join() Returns a string with elements from an Array
pop() Removes the last value from an Array
push() Appends a value to the end of an Array
reverse() Reverse the order of elements in an Array
shift() Removes the first value from an Array
slice() Returns a subset from an Array
sort() Sorts an Array
splice() Adds new elements to an Array while removing old elements.
toLocaleString() Returns a String with current locale format and separators
toSource() String representing the source code of the object
toString() Returns Array elements as string type separated by commas
unshift() Inserts a value at the beginning of an Array
valueOf() Returns Array elements as string type separated by commas
constructor() Reference to the function that created an object
index() Zero-based index of the match for array created by a regular expression match
input() Original string used to match for array created by a regular expression match
length() Returns the length of an Array
prototype() Creates a new method for Array objects

Example

var colors = new Array('red', 'green', 'blue');
colors.push('black');
document.write(colors);

Javascript Methods for Booleans

Method Usage
toSource() String representing the source code of the object
toString() Returns boolean value as string type
valueOf() Returns an objects value as a Boolean type
constructor() Reference to the function that created an object
prototype() Creates a new method for Boolean objects

Example

var x = 3;
result = x.valueOf();
document.write(result);

Date Methods

Method Usage
getDate() Date as an integer between 1 and 31
getDay() Day of week value: 0=Sunday, 1=Monday
getYear() Year value of a Date object
getFullYear() 4 digit year of a Date object
getHours() Hours value of a Date object (0-23)
getMilliseconds() Milliseconds value of a Date object (0-999)
getMinutes() Minutes value of a Date object (0-59)
getMonth() Month value of a Date object (0=Jan, 11=Dec)
getSeconds() Seconds value of a Date object (0-59)
getTime() Milliseconds since 1970-1-1 of a Date object
getTimezoneOffset() Minutes between local and UTC (GMT) time
getUTCDate() Date value using UTC (GMT) time
getUTCDay() Day of week using UTC (GMT) time (0=Sunday)
getUTCFullYear() 4 digit year using UTC (GMT) time
getUTCHours() Hours using UTC (GMT) time. (0-23)
getUTCMilliseconds() Milliseconds using UTC (GMT) time (0-999)
getUTCMinutes() Minutes using UTC (GMT) time (0-59)
getUTCMonth() Month using UTC (GMT) time (0-11)
getUTCSeconds() Seconds using UTC (GMT) time (0-59)
parse() Milliseconds between parsed string and 1970-1-1
setDate() Sets the date of the Date object
setFullYear() Sets the year value in a Date object
setHours() Sets the hours value in a Date object
setMilliseconds() Sets the milliseconds value in a Date object
setMinutes() Sets the minutess value in a Date object
setMonth() Sets the month value in a Date object
setSeconds() Sets the seconds value in a Date object
setTime() Sets the time value (milliseconds) in a Date object
setUTCDate() Sets the UTC date of a Date object
setUTCFullYear() Sets the UTC year value in a Date object
setUTCHours() Sets the UTC hours value in a Date object
setUTCMilliseconds() Sets the UTC milliseconds value in a Date object
setUTCMinutes() Sets the UTC minutess value in a Date object
setUTCMonth() Sets the UTC month value in a Date object
setUTCSeconds() Sets the UTC seconds value in a Date object
setYear() Sets the year value of a Date object
toDateString() Returns a date as a string value
toGMTString() String value of a Date objects GMT time
toLocaleDateString() Returns a date as a string value
toLocaleString() String value of a Date object, in local time format
toLocaleTimeString() Returns a time as a string value
toSource() String representing the source code of the object
toString() String representation of a Date object
toTimeString() Returns a time as a string value
toUTCString() Date converted to string using UTC
UTC() Milliseconds since 1970 using UTC time
valueOf() Milliseconds since 1970-1-1
constructor() Reference to the function that created an object
prototype() Creates a new method for Date objects

Example

var myDate=new Date();
alert('Current date and time is: '+myDate.toLocaleString());

Object Methods

Method Usage
Object Provides functionality common to all JavaScript objects
toLocaleString() String value of an object, in local value format
toSource() Object literal representing the specified object
toString() Returns a string representing the object
unwatch() Removes a watchpoint set with the watch method
valueOf() Primitive value of the specified object
watch() Runs a function when specific property is assigned value
constructor Reference to the function that created an object
prototype Creates a new method for Number objects
apply() Applies a method of another object to the current object
call() Executes method of another object on current object
toSource() String representing the source code of the function
toString() String representing the source code of the function
valueOf() String representing the source code of the function
arguments() An array with the arguments passed to a function
arguments.callee() The function body of the currently executing function
arguments.length() Number of arguments passed to the function
caller Reference to the function that created an object
constructor() Reference to the function that created an object
length() Number of arguments expected by the function
prototype() Creates a new method for Function objects

Example

var username = 'webtrickshome';
alert (username.length);

Global Methods

Method Usage
decodeURI() Decodes a URI
decodeURIComponent() Decodes an encoded URI component
encodeURI() Encodes a text string as a URI
encodeURIComponent() Encodes a text string as a component of a URI
escape() Encodes Strings so they can be read on all computers
eval() Evaluates string and executes it as if it was script code
isFinite() Determines whether a value is a finite number
isNaN() Evaluates an argument to determine if it is not a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
unescape() Decodes String objects encoded with the escape method
Infinity Returns an initial value of Number
NaN Returns NaN indicating that an expression is not a number
undefined Returns value of undefined

Example

var x = "This is a string";
alert(escape(x));

Arithmetic Methods

Method Usage
abs() Returns the absolute value of a number
acos() Returns the arccosine (in radians) of a number
asin() Returns the arcsine (in radians) of a number
atan() Returns the arctangent (in radians) of a number
atan2() Returns the arctangent of the quotient of its arguments
ceil() Returns the smallest integer greater than or equal to a number
cos() Returns the cosine of a number
exp() Returns e (the base of natural logarithms) raised to a power
floor() Returns the largest integer less than or equal to a number
log() Returns the natural logarithm (base E) of a number
max() Returns the greater of two numbers
min() Returns the lesser of two numbers
pow() Returns the value of a base expression taken to a specified power
random() Returns a pseudo random number between 0 and 1
round() Returns the value of a number rounded to the nearest integer
sin() Returns the sine of a number
sqrt() Returns the square root of a number
tan() Returns the tangent of a number

Example

document.write('The square root of 9 is: '+Math.sqrt(9))

Numeric Objects

Method Usage
Number Object for primitive numeric values
toLocaleString() String value of a Number object, in local value format
toString() Returns a string representing the object
valueOf() The numeric value
constructor Reference to the function that created an object
MAX_VALUE Largest number representable. (~1.79E+308)
MIN_VALUE Smallest number representable. (~5.00E-324)
NaN Special "not a number" value
NEGATIVE_INFINITY Negative infinity, displayed as "-Infinity"
POSITIVE_INFINITY Positive infinity, displayed as "Infinity"
prototype Creates a new method for Number objects

Example

myDOB = new Number(65);
document.write('I was born in '+myDOB);

String Object

Method Usage
length Returns the length of the string
charAt(n) Returns the character at the specified position in the string
charCodeAt(n) Returns the character code at the specified position in the string
indexOf(string[,n]) Returns the first position of the substring
lastIndexOf(substring[,n]) Returns the last position of the substring
fromCharCode(x[,y,z]) Constructs a string from the specified sequence of ISO-Latin-1 codeset values
substring(x,y) Returns the specified subset of the string, by specifying the start and end indexes
toLowerCase() Returns the string in all lowercase
toUpperCase() Returns the string in all uppercase
split(separator[,n]) Splits a string into an array of strings by separating the string into substrings
slice(x,y) Does exactly the same as substring
substr(x,y) Returns a subset of a string
match Compare variables
replace(/subtext/[gi]) Replaces substrings of a string
search Searches for substrings in a string

Example

name = 'webtrickshome';
alert(name.indexOf('b'));

navigator Objects

The navigator object contains information about the browser.

Method Usage
appCodeName Specifies the code name of the browser
appName Specifies the name of the browser
appVersion Specifies version information for the browser
userAgent Specifies the user agent header
mimeTypes An array of all MIME types supported by the visitors browser
plugins An array of all plug-ins currently installed on the visitors browser
javaEnabled Tests whether Java is enabled
plugins.refresh Makes newly installed plug-ins available and can reload windows containing plug-ins
taintEnabled Specifies whether data tainting is enabled
platform Indicates the platform (Win32, Unix, etc.) for which the browser was compiled
language Indicates the language version of the browser
preference Allows a signed script to get and set certain Navigator preferences

Example

name = navigator.appName;
alert(name);

window Objects

The window method is the top level method in Javascript. It can represent either a top level window or a frame inside a frameset.

Method Usage
onDragDrop Triggered when a user drops an object,such as a file, onto the browser window
onLoad Triggered when a browser finishes loading a window or all of the frames within a FRAMESET tag
onMove Triggered when a user or script moves a window or frame
onResize Triggered when a user or script resizes a window or frame
onUnload Triggered when a user exits a document
onBlur Triggered when a form element loses focus or when a window or frame loses focus
onError Triggered when the loading of a document or image causes an error
onFocus Triggered when a window, frame, or frameset receives focus or when a form element receives input focus
defaultStatus Reflects the default message displayed in the window's status bar
document Contains information on the current document, and provides methods for displaying HTML output to the user
frames An array reflecting all the frames in a window
length The number of frames in the window
location Contains information on the current URL
name A unique name used to refer to the window
parent A synonym for a window or frame whose frameset contains the current frame
self A synonym for the current window
status Specifies a priority or transient message in the window's status bar
top A synonym for the top most browser window
window A synonym for the current window
alert Displays an Alert dialog box with a message and an OK button
clearTimeout Cancels a timeout that was set with the setTimeout method
close Closes the specified window
confirm Displays a Confirm dialog box with the specified message and OK and Cancel buttons
open Opens a new web browser window
print Prints the contents of the window or frame
prompt Displays a Prompt dialog box with a message and an input field
setTimeout Evaluates an expression or calls a function once after a specified number of milliseconds has elapsed
closed Specifies whether a window has been closed
history Contains information on the URLs that the client has visited within a window
opener Specifies the window name of the calling document when a window is opened using the open method
blur Removes focus from the specified object
focus Gives focus to the specified object
scroll Scrolls a window to a specified coordinate
innerHeight Specifies the vertical dimension, in pixels, of the window's content area
innerWidth Specifies the horizontal dimension, in pixels, of the window's content area
outerHeight Specifies the vertical dimension, in pixels, of the window's outside boundary
outerWidth Specifies the horizontal dimension, in pixels, of the window's outside boundary
pageXOffset Provides the current x-position, in pixels, of a window's viewed page
pageYOffset Provides the current y-position, in pixels, of a window's viewed page
personalbar Represents the browser window's personal bar (also called the directories bar)
scrollbars Represents the browser window's scroll bars
statusbar Represents the browser window's status bar
toolbar Represents the browser window's tool bar
back Undoes the last history step in any frame within the top level window
captureEvents Sets the window or document to capture all events of the specified type
clearInterval Cancels a timeout that was set with the setInterval method
disableExternalCapture Disables external event capturing set by the enableExternalCapture method
enableExternalCapture Allows a window with frames to capture events in pages loaded from different locations (servers)
find Finds the specified text string in the contents of the specified window
forward Loads the next URL in the history list
handleEvent Invokes the handler for the specified event
home Points the browser to the URL specified in preferences as the user's home page
locationbar Represents the browser window's location bar
menubar Represents the browser window's menu bar
moveBy Moves the window by the specified amounts
moveTo Moves the top left corner of the window to the specified screen coordinates
releaseEvents Sets the window to release captured events of the specified type, sending the event to objects further along the event hierarchy
resizeBy Resizes an entire window by moving the window's bottom right corner by the specified amount
resizeTo Resizes an entire window to the specified outer height and width
routeEvent Passes a captured event along the normal event hierarchy
scrollBy Scrolls the viewing area of a window by the specified amount
scrollTo Scrolls the viewing area of the window to the specified coordinates, such that the specified point becomes the top left corner
setInterval Evaluates an expression or calls a function every time a specified number of milliseconds elapses
stop Stops the current download

Example

<body onload="return myFunction()">
<script>
  function myFunction(){
    document.write('Hello World!');
  }
</script>
</body>

window.location Objects

The window.location object contains information on the current URL. It represents the complete URL of a document and each property of the location object represents a different portion of the URL.

Method Usage
hash Specifies an anchor name in the URL
host Specifies the host and domain name, or IP address, of a network host
hostname Specifies the host:port portion of the URL
href Specifies the entire URL
pathname Specifies the URL path portion of the URL
port Specifies the communications port that the server uses
protocol Specifies the beginning of the URL, including the colon
search Specifies a query
reload Forces a reload of the window's current document
replace Loads the specified URL over the current history entry

Example

var url = window.location.href;
alert(url);

window.history Objects

The window.history object contains an array of information on the URLs that the client has visited within a window.

Method Usage
length Returns number of entries in the history list
back Loads the previous URL in the history list
forward Loads the next URL in the history list
go Loads a URL from the history list
next Specifies the URL of the next history entry
previous Specifies the URL of the previous history entry
current Specifies the URL of the current history entry

Example

var url = window.history.length;
alert(url);

window.document Objects

The window.document object contains information about the current document and provides methods for displaying HTML output to the user.

Method Usage
onClick An object on a form is clicked
onDblClick The user double clicks a form element or a link
onKeyDown The user depresses a key
onKeyPress The user presses or holds down a key
onKeyUp The user releases a key
onMouseDown The user depresses a mouse button
onMouseUp The user releases a mouse button
alinkColor A string that specifies the ALINK attribute
anchors An array containing an entry for each anchor in the document
bgColor A string that specifies the BGCOLOR attribute
cookie Specifies a cookie
fgColor A string that specifies the TEXT attribute
lastModified A string that specifies the date the document was last modified
linkColor A string that specifies the LINK attribute
links An array containing an entry for each link in the document
referrer A string that specifies the URL of the calling document
title A string that specifies the contents of the TITLE tag
URL A string that specifies the complete URL of a document
vlinkColor A string that specifies the VLINK attribute
close Closes an output stream and forces data to display
open Opens a stream to collect the output of write or writeln methods
write Writes one or more HTML expressions to a document in the specified window
writeln Writes one or more HTML expressions to a document in the specified window and follows them with a newline character
applets An array containing an entry for each applet in the document
domain Specifies the domain name of the server that served a document
embeds An array containing an entry for each plug-in in the document
formName A separate property for each named form in the document
forms An array a containing an entry for each form in the document
images An array containing an entry for each image in the document
plugins An array containing an entry for each plug-in in the document
layers Array containing an entry for each layer within the document
captureEvents Sets the document to capture all events of the specified type
getSelection Returns a string containing the text of the current selection
handleEvent Invokes the handler for the specified event
releaseEvents Sets the window or document to release captured events of the specified type, sending the event to objects further along the event hierarchy
routeEvent Passes a captured event along the normal event hierarchy

Example

var date = document.lastModified;
document.write(date);

0 Like 0 Dislike 0 Comment Share

Leave a comment