JavaScript Document Object

JavaScript Document object is an object that provides access to all HTML elements of a document. When an HTML document is loaded into a browser window, then it becomes a document object.

The document object stores the elements of an HTML document, such as HTML, HEAD, BODY, and other HTML tags as objects.

A document object is a child object of the Window object, which refers to the browser.

You can access a document object either using window.document property or using object directly.

See, What we can do with Document Object:

  • Suppose you have created a FORM in an HTML document using the FORM element and added some text fields and Buttons on the Form. On Submitting the Form you want to validate the input or display input on another page. In this situation, you can use a document object which is a child object of the window object. Using the document object, you can access the elements of the form and validate the Input.
  • The Document Object provides different collection elements, such as anchor and Links which helps you to count the number of specific elements on a form.
  • The Document Object also provides various properties such as URLbgcolor, etc. which will allow you to retrieve the details of a document and various methods such as open()close()write(), getElementById()getElementByName(), etc. which allow you to perform various tasks like opening an HTML document to display output and writing a text on Web Page.
  • The Document Object also allows you to create cookies for a webpage by providing a property named cookie. A cookie stores information about the user’s computer, which helps in accessing visited websites.

Now let’s explore document object methods and properties.

JavaScript Document Object Properties

As we know, a property of an object is the value associated with the object. The property is accessed by using the following notation:

objectName.propertyName

where objectName is the name of the object and propertyName is the name of its property.

Now we will show you the properties of document object in the table given below:

PropertiesDescription
cookiereturns a report that contains all the visible and unexpired cookies associated with the document
domainreturns the domain name of the server from which the document has originated
lastModifiedreturns the date on which document was last modified
documentModereturns the mode used by the browser to process the document
readyStatereturns the loading status of the document.
referrerreturns the URL of the documents referred to in an HTML document
titlereturns the name of the HTML document defined between the starting and ending tags of the TITLE element
URLreturns the full URL of the HTML document.

Let’s take an example, to see the document object properties in action:


JS Document Methods Example

Document Methods Example

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Document Object Methods

JavaScript Document object also provides various methods to access HTML elements.

Now we will show you some of the commonly used methods of the document object:

MethodsDescriptionSyntax
open()opens an HTML document to display the outputdocument.open(mimetype, replace)
close()closes an HTML documentdocument.close()
write()Writes HTML expressions or JavaScript code into an HTML documentdocument.write(exp1, exp2, ...)
writeln()write a new line character after each HTML expressions or JavaScript Codedocument.writeln(exp1, exp2, ...)
getElementById()returns the reference of first element of an HTML document with the specified id.document.getElementById(id)
getElementByName()returns the reference of an element with the specified namedocument.getElementsByName(name)
getElementsByTagName()returns all elements with the specified tagnamedocument.getElementsByTagName(tagname)

Now let’s take an example, to see the document object methods like open()write(), and getElementById() to explain their usage. See the below example:

It Will change

    <script>
        // Open document
        document.open();
        // writing
        document.write("Hello" +"<br>");
        document.getElementById("demo").innerHTML = "Set by ID";
    </script>
</body>

JavaScript Screen Object

JavaScript Screen is a built-in Interface (object type) that is used to fetch information related to the browser screen on which the current window is rendered.

It provides information about the dimensions of the display screen such as its height, width, color bits, etc.

Since the window object is at the top of the scope chain, the property window.screen gives the Screen object, but the screen object can be accessed without specifying the window too, in that case JavaScript automatically detects the browser window, which is created by JavaScript Runtime Engine.

Let’s take a simple example to see the working of the screen object.
JS Screen Object Example

JavaScript Screen Object

    <script>
        document.writeln("Total Height: " + screen.height +"<br>");
        document.writeln("Total Width: " + screen.width +"<br>");
    </script>
</body>

JavaScript Screen Object Properties

JavaScript Screen object includes some properties that are used to get browser screen information. A table of such properties is given below.

PropertyDescription
availHeightspecifies the height of screen, excluding the windows taskbar
availWidthspecifies the width of the screen, excluding the Windows taskbar
colorDepthspecifies the depth of color palette, in bits, to display images
heightspecifies the total height of the screen
pixelDepthspecifies the color Resolution, in bits per pixel, of the screen
widthspecifies the total width of the screen

The Screen object colorDepth property is the number of bits used to represent the color of a single pixel. It returns the bit depth of the color palette for displaying images.

JavaScript Screen Object Methods

There are no direct methods in the Screen method object.

Uses of Screen Object

The JavaScript Screen object can be used for improving the user experience by controlling the UI of the web app or website based on the screen size.

JavaScript Location Object

JavaScript Location is a built-in Interface (object type) which represents the location (URL) of the object to which it is attached. Both the Window object and the Document object have this property. The window objects location property gives us access to the browser window’s location whereas the document location property gives us the location object for a particular document.

It is used to fetch information of the current URL. The Location object allows you to navigate to another webpage as well.

Get Website Host name

    <script>
         var x = location.hostname;
        document.write(x);

    </script>
</body>

There are many different properties of the location object and many methods too.

JavaScript Location Object Properties

JavaScript Location Object has many properties using which we can access the various components of a webpage’s URL and even change it.

Here are some commonly used properties for the location object:

PropertyDescription
hrefRepresents a string specifying the entire URL, for instance
protocolRepresents a String at the begining of a URL to the first colon(:),which specifies the Method of access to the URL , for instance http: or https:
hostRepresents a String consisting of hostname and port Strings,for instance:- http://www.javascriptstudytonight.com:80
hostnameRepresents the server name, subdomain, and domain name (or IP address)of a URL, for instance http://www.javascriptstudytonight.com
portRepresents a string specifying the communication port that the server uses, for instance 80
pathnameRepresents a String Portion of a URL, specifying how a particular resource can be accessed, for instance: order.cgi
searchRepresents a string beginning with a question mark that specifies any query information in an HTTP URL, for instance batch=1
hashRepresents a string beginning with a hash(#), which specifies an anchor name in an HTTP URL, for instance #intro

Let’s take an example and get to know about the properties of Location object.

Location Properties

    <script>
        // Hostname
        let x = location.hostname;
        document.write(x +"<br>");
        // href
        x = location.href;
        document.write(x +"<br>");
        // protocol
        x = location.protocol;
        document.write(x +"<br>");
        // host
        x = location.host;
        document.write(x +"<br>");
        // pathname
        x = location.pathname;
        document.write(x +"<br>");
    </script>
</body>

Now let’s see the methods of the location object.

JavaScript Location Object Methods

Location Object methods refers to the functions created inside the location interface which can be used to perform various operations on the URL like reload it, change it, etc.

MethodDescription
assign()Loads a new Document in the Browser
reload()Reloads the current document that is contained in location.href property.
replace()Replaces the current document with the specified new one. In addition, you cannot navigate back to the previous document using the Browser’s back button.

To load a new document, We can use the assign() method of Location object. But in this example, we have used the href property and the replace() methods too. They all can be used to load a document.

Location Methods example

    <button onclick="load1()">visit studytonight.com</button>
    <button onclick="load2()">visit studytonight.com</button>
    <button onclick="load3()">visit studytonight.com</button>

    <script>
        // assign method
        function load1(){
            location.assign("https://www.studytonight.com");
        }

        // href
        function load2(){
            location.href="https://www.studytonight.com";
        }

        // replace()
        function load3(){
            location.replace("https://www.studytonight.com");
        }

    </script>
</body>

JavaScript History Object

JavaScript History is a built-in Interface (object type) which is used to access the browser window session history. It contains the list of URLs visted by a user in a particular browser window, tab or frame, represented by the window object.

The history object is a property of the JavaScript window object, and can be accessed through the window.history property, and is used to access the session history for that window object.

It provides useful methods and properties that let us navigate back and forth through the window’s session history.

Let’s take an example to see how this works to understand it better.

JavaScript History Object Example

The History object’s back() method is used to go back to the previous URL accessed in the browser window, in the history list.

It is same as clicking the “Back button” in your browser.

<button onclick="goBack()">Go Back</button>

<script>
	function goback(){
	    window.history.back();
	}
</script>

Similarly, we can use the history object’s forward() method to load the next URL in the history list. If next URL is not present, it does nothing.

It is same as clicking the “Forward button” in your browser.

<button onclick="goforward()">Go Forward</button>

<script>
	function goforward(){
	    window.history.forward();
	}
</script>

Apart from the back() and forward(), JavaScript history object provides more methods like go()which can be used to jump to any specific URL present in the history object.

To move to any specific page, we can use the go() method, it takes an integer argument that works as an index value for history URL list. See the below example:

<script>
    // move to one page backward
	window.history.go(-1);

    // move to two page backward
    window.history.go(-2);

    // move to one page forward
    window.history.go(1);

    // move to two page forward
    window.history.go(2);
</script>

We can also use the go() method of history object to refresh the current page. In the example below, we have called the go() method two times and it works the same in the both scenario. We can call it anytime when we want to refresh/reload the current page.

<script>
// Refresh the page
        window.history.go(0);

        window.history.go();

</script>

JavaScript History Object Property

Following are the properties of the History object. The length property is used the most.

PropertiesDescription
lengthspecifies the number of elements contained in the object
scrollRestorationallows web applications to explicitly set default scroll restoration behavior on history navigation
staterepresents the state at the top of the history stack

Let’s take an example to get number of pages visited by a user in a browser window. We will use the length property that contains information for the visited pages.

JavaScript History Object Methods

JavaScript History object methods refer to the functions created inside the history object. These methods specify the actions related to the URLs visited in the Browser window’s current session.

MethodsDescription
back()specifies a method that loads the previous URL from the history list.
forward()specifies a method that loads the next URL from the history list.
go()specifies a method that loads a specific URL from the history list.
pushState()used to push the given data onto the session history stack with the specified title
replaceState()used to update the most recent entry on the history stack to the specified data, title, and, if provided, URL

We have explained each method with examples in the beginning of this tutorial itself.

In the next tutorial we will learn about the Navigator browser object.

JavaScript Window Object

JavaScript Window is a global Interface (object type) which is used to control the browser window lifecycle and perform various operations on it.

A global variable window, which represents the current browser window in which the code is running, is available in our JavaScript code and can be directly accessed by using window literal.

It represents a window containing a webpage which in turn is represented by the document object. A window can be a new window, a new tab, a frame set or individual frame created with JavaScript.

In case of multi tab browser, a window object represents a single tab, but some of its properties like innerHeightinnerWidth and methods like resizeTo() will affect the whole browser window.

Whenever you open a new window or tab, a window object representing that window/tab is automatically created.

The properties of a window object are used to retrieve the information about the window that is currently open, whereas its methods are used to perform specific tasks like opening, maximizing, minimizing the window, etc.

To understand the window object, let’s use it to perform some operations and see how it work.

Using JavaScript Window Object

Let’s use the JavaScript window object to create a new window, using the open() method. This method creates a new window and returns an object which further can be used to manage that window.

Click to open a new Window:

    <button onclick="createWindow()">Open a Window</button>
    <p id="result"></p>

    <script>
    function createWindow() {
        let url = "https://studytonight.com";
        let win = window.open(url, "My New Window", "width=300, height=200");
        document.getElementById("result").innerHTML = win.name + " - " + win.opener.location;
    }
    </script>

In the code above, we have used the window object of the existing window to create a new window using the open() method. In the open() method we can provide the URL to be opened in the new window(we can keep it blank as well), name of the window, the width and the height of the window to be created.

Following is the syntax for the window object open() method:

let newWindow = window.open(url, windowName, [windowFeatures]);

We can provide, as many properties as we want, while creating a new window.

When the open() method is executed, it returns the reference of the window object for the new window created, which you can assign to a variable, like we have done in the code above. We have assigned the value returned by the window.open() method to the win variable.

The we have used the win variable to access the new window, like getting the name of the window, getting location of the window which opened the new window etc.

There are many properties and methods for the window object, which we have listed down below.

Find Dimensions of a Window

We can get the height and width of a window by using the window object built-in properties.

We can also access the document object using a window object(window.document) which gives us access to the HTML document, hence we can add new HTML element, or write any content to the document, like we did in the example above.

JavaScript Window Object Properties

The wondow object properties refer to the variables created inside the windows object.

In JavaScript, all the available data is attached to the window object as properties.

We can access window object’s properties like: window.propertynamewhere propertyname is the name of property.

A table of most popular window object properties is given below:

PropertyDescription
closedreturns a boolean value that specifies whether a window has been closed or not
documentspecifies a document object in the window.
historyspecifies a history object for the window.
framesspecifies an array of all the frames in the current window
defaultStatusspecifies the default message that has to be appeared in the status bar of Window.
innerHeightspecifies the inner height of the window’s content area.
innerWidthspecifies the inner width of the window’s content area.
lengthspecifies the number of frames contained in the window.
locationspecifies the location object for window
namespecifies the name for the window
topspecifies the reference of the topmost browser window.
selfreturns the reference of current active frame or window.
parentreturns the parent frame or window of current window.
statusspecifies the message that is displayed in the status bar of the window when an activity is performed on the Window.
screenleftspecifies the x coordinate of window relative to a user’s monitor screen
screenTopSpecifies the y coordinate of window relative to a user’s monitor screen
screenXspecifies the x coordinate for window relative to a user’s monitor screen
screenYSpecifies the y coordinate for window relative to a user’s monitor screen

In the example above, we have created a new window, just to make you familiar with new window creation and also, to make you understand that when we create a new window, then the current window has a different window object and the new window will have a separate window object.

We have then tried to access some properties of the new window created.

TASK: Try some more windows property in the above code playground to practice and understant how window properties work.

JavaScript Window Object Methods

The window object methods refer to the functions created inside the Window Object, which can be used to perform various actions on the browser window, such as how it displays a message or gets input from the user.

Below we have listed down some of the most commonly used window object methods:

MethodDescription
alert()specifies a method that displays an alert box with a message an OK button.
blur()specifies a method that removes the focus from the current window.
clearInterval()specifies a method that clears the timer, which is set by using setInterval() method.
close()specifies a method that closes the current window.
confirm()specifies a method that displays a dialogue box with a message and two buttons OK and Cancel
focus()specifies a method that sets the focus on current window.
open()specifies a method that opens a new browser window
moveTo()specifies a method that moves a window to a specified position
moveBy()specifies a Method that moves a window relative to its current position.
prompt()specifies a method that prompts for input.
print()specifies a method that sends a print command to print the content of the current window.
setTimeout()specifies a method that evaluates an expression after a specified number of milliseconds.
setInterval()specifies a method that evaluates an expression at specified time intervals (in milliseconds)
resizeBy()specifies the amount by which the window will be resized
resizeTo()used for dynamically resizing the window
scroll()scrolls the window to a particular place in document
scrollBy()scrolls the window by the given value
stop()this method stops window loading

In the example above, we have used some window methods, you can try more methods. In the next tutorial we will learn about the History object, which is a property of the window object.

JavaScript Browser Object Model

JavaScript provides WebAPIs and Interfaces(object types) that we can use while developing web application or website. These APIs and objects help us in controlling the lifecycle of the webpage and performing various actions like getting browser information, managing screen size, opening and closing new browser window, getting URL information or updating URL, getting cookies and local storage, etc.

There is so much that you can do using these WebAPIs and Interfaces. All the supported Web APIs and Interfaces in JavaScript are listed on the Mozilla Developer website.

The Iterfaces (object types) which help us interact with the browser window are known as Browser objects. Browser object is not an official term but its a group of objects which belongs to different WebAPIs but are used for managing various browser related information and actions.

For example, when an HTML document is opened in a browser window, the browser interprets the document as a collection of hierarchical objects(HTML tags) and accordingly displays the data contained in these objects(HTML page rendering). The browser parses the document and creates a collection of objects, which defines the documents and its details. We have shown the various objects that can be used to access various components of the browser window in the picture below:

The browser objects are of various types, used for interacting with the browser and belongs to different APIs. The collection of these Browser objects is also known as Browser object Model(BOM).

The default object of browser is Window which means you can call its functions directly.

Browser Objects:

The objects listed below are called browser objects.

  • Window – part of DOM API
  • Navigator
  • Document – part of DOM API
  • Screen – property of Window object
  • History – property of Window object
  • Location – property of Window and Document object

Window Object

It is used to interact with the browser window which displays the web page. It generally represents a tab in browser, but some actions like window width and height will affect the complete browser window.

We have covered JavaScript Window Object separately, in detail.

Navigator Object

It acts as a storehouse of all the data and information about the Browser software used to access the webpage and this object is used to fetch information related to the browser for example, whether the user is using Chrome browser or Safari browser, which version of browser is being used etc.

We have covered JavaScript Navigator Object separately, in detail.

Document Object

This object represent the HTML document that is loaded into the browser. A document object is an object that provides access to all HTML elements of a document(webpage). We can use this object to append a new HTML tag to the webpage, modify any exsiting HTML tag, etc.

We have covered JavaScript Document Object separately, in detail.

History Object

It stores Uniform Resource Locator(URLs) visited by a user in the browser. It is a built-in object which is used to get browser history. This object is a property of the JavaScript Window object.

We have covered JavaScript History Object separately, in detail.

Screen Object

It is a built-in object which is used to fetch information related to the browser screen, like the screen size, etc. It is also obtained from the Window object.

We have covered JavaScript Screen Object separately, in detail.

Location Object

Location is a built-in object which represent the location of the object to which it is linked, which can be Window or Document. Both the Document and Window interface have a linked location property.

We have covered JavaScript Location Object separately, in detail.

JavaScript RegExp Object

The regular expression or JavaScript RegExp is an object that helps you to validate the pattern of characters in a string or match a string, etc. You can use the JavaScript RegExp object to validate an e-mail entered in a form, or maybe check if a Pincode is all numeric, or a password has alphanumeric and special characters, etc.

There are two ways of defining regular expression in JavaScript.

1. Using the JavaScript RegExp object’s constructor function

2. Using Literal syntax

Creating JavaScript RegExp Object

Let’s see how we can create a RegExp object in JavaScript:

// Object Syntax
let regExp = new RegExp("pattern", "flag");

// Literal Syntax
let regExp = /pattern/flag;

Where the pattern is the text of regular expression, the flag makes the regular expression search for a specific pattern.

Note: In this tutorial, we will discuss the RegExp object, its properties and methods. All the examples will be based on the RegExp object, not the literal regular expression. We have covered the regex literal syntax earlier.

We will be using the following String methods to use the RegExp object to test, match, and validate various string values in JavaScript:

  • test()
  • match()
  • replace()
  • exec()

Let’s take a few examples to understand the use of the JavaScript RegExp object.

Creating a RegExp to match IP address

To match all the strings that look like IP address: xxx.xxx.xxx.xxx, we can use the following regex pattern:

let regularexp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g;

Now let’s create an example to validate an IP address. The below code returns true if the given IP address is valid:

let str = "102.235.251.251";
// regex pattern to match valid ip
let re = new RegExp(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
// test the regex
let result = re.test(str);
if(result)
	document.write("Ip address is valid");
else
	document.write("Ip address is not valid");

Ip address is valid

How to replace a string using Regex?

Let’s see an example to replace a part of the string or the complete string with some other string or replace the order of the string using a regular expression.

// Creating regex object
let re = new RegExp(/(\w+)\s(\w+)/);
let str = 'Mohan Shyam';
// Replacing string
let newstr = str.replace(re, '$2, $1');
document.write(newstr);

Shyam, Mohan

Fetch Subdomain Value from a Domain Name

We can use a regular expression to fetch the subdomain from a URL. The RegExp exec() method is used to perform regular expression pattern matching, and return an array of string. See the below example:

let url = 'http://linux.studytonight.com';
// Creating regex object
let re = new RegExp(/[^.]+/);
let result = re.exec(url)[0].substr(7);
document.write(result);

linux

Find a Pattern in String

To find a pattern in string, we can use the string match() method. It returns the match pattern that can be a substring. See the below example:

// Creating regex object
var regex = new RegExp(/India/g);
var str = "We live in India.";
// search for India
var matches = str.match(regex);
document.write(matches);

India

Properties of JavaScript RegExp Object

  • global: refers that g modifier is set.
  • ignoreCase: refers that i modifier is set
  • lastIndex: refers to the index to start the next match.
  • multiline: Refers that m modifier is set.
  • source: refers to the text of the RegExp pattern.

JavaScript RegExp ignoreCase Property:

The ignoreCase property indicates whether or not the i flag is used with the regular expression. The ignoreCase is a read-only property of the RegExp object.

var re = new RegExp("/hello/","i");
// ignorecase property
var result = re.ignoreCase;
document.write(result);

true

MethodDescription
exec()Executes a search for a match in a string. It returns an array of information or null on a mismatch.
test()Tests for a match in a string. It returns true or false.
match()Returns an array containing all of the matches, including capturing groups, or null if no match is found.
matchAll()Returns an iterator containing all of the matches, including capturing groups.
search()Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace()Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split()Uses a regular expression or a fixed string to break a string into an array of substrings.

RegExp test() Method Example

The RegExp test() method is used to test the regular expression and it returns true if the expression matches.

<script>
	var str = "Hello";
	var re = new RegExp("/hello/","i");
	var result = re.test(str);
	document.write(result)

</script>

true

Validate Email using Regular Expression

Let’s validate an email address by using a regular expression. In the below example, we are validating email for the user to ensure that user enters valid email only.

let str = "abc@gmail.com";
// regex pattern to match valid email
let re = new RegExp(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
// test the 
let result = re.test(str);
if(result)
    document.write("Email is valid")
else
    document.write("Email is not valid")

Email is valid

JavaScript Date Object

JavaScript Date object is a built-in object which is used to deal with date and time. It stores a Number which represents milliseconds for the Unix Timestamp(which is nothing but milliseconds passed since 1 January 1970 UTC). We can use it to create a new date, format a date, get elapsed time between two different time values, etc.

It also helps to get a date value using milliseconds number and we can get a date based on the different timezones as well.

The Date object use browser’s date timezone by default and display date in the text format.

The Date object can be created using the Date constructor function.

Creating the JavaScript Date Object

Let’s see how we can create the Date object in JavaScript. Although there are multiple ways of doing it, the default way is using the new keyword with the Date constructor function.

let newdate = new Date();

The above will create a new Date object with the current date and time stored in it. The format of the date stored in this object will be:

Tue May 05 2020 21:16:17 GMT+0530 (India Standard Time)

Yes, it will be the complete date and time along with timezone information.

To get the standard UNIX timestamp value we can use the following code:

let newdate = Date.now();

1588693792007

In the code above we have used the static function now() for the Date object. This will give us the Unix timestamp for current date and time which is nothing but the number of milliseconds passed since 1 January 1970.

Other Ways to Create JavaScript Date

Apart from the above two syntaxes, there are multiple other ways to create a date in JavaScript. Here, we are using different syntax to create date objects.

<!doctype html>
	<head>
		<title>JS Date Example</title>
	</head>
	<body>
		<script>
			/* JS comes here */
            let date1 = new Date('February 13, 1991 06:44:00');
            let date2 = new Date('1991-02-13T06:44:00');
            let date3 = new Date(1991, 02, 13);    // the month is 0 indexed
            let date4 = new Date(1991, 02, 13, 6, 44, 0);
            document.write("Example 1: " + date1);
            document.write("<br/>Example 2: " + date2);
            document.write("<br/>Example 3: " + date3);
            document.write("<br/>Example 4: " + date4);
		</script>
	</body>
</html>

As you can see in the examples above, we can create a date for a custom date which can be a past date or a future date. We can even provide the time value.

Working with JavaScript Date

JavaScript Date constructor handles different formats to create a date, we can pass a string format date or a numerical literal with milliseconds to create a date object in JavaScript.

Creating JavaScript Date using String

JavaScript allows the following string formats to create a date object.

let date1 = new Date('February 13, 1991 06:44:00')
document.write(date1 +"<br>");

let date2 = new Date('1991-02-13T06:44:00');
document.write(date2);

Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time) Wed Feb 13 1991 06:44:00 GMT+0530 (India Standard Time)

Creating JavaScript Date using Numerical Literal

We can use the Date() constructor can take 7 arguments to create a date, which is: yearmonthdayhourminutesecond, and millisecond.

We can also get a date by just passing milliseconds too. See the below example:

let date1 = new Date(2018,11,25,12,25,12,0);
document.write(date1 +"<br/>");

// Passing miliseconds
let date2 = new Date(1825356800000);
document.write(date2);

Tue Dec 25 2018 12:25:12 GMT+0530 (India Standard Time) Fri Nov 05 2027 01:03:20 GMT+0530 (India Standard Time)

Get Year, Month and Day from a JavaScript Date

To get the value for the year, month or day from a date, we can use JavaScript built-in methods. These methods are easy to use and reduce the effort and time for coding.

// Creating a date
let date1 = new Date(2018,11,25,12,25,12,0);

// Getting year
let year = date1.getFullYear();
document.write("<br> Year: "+  year);

// Getting Month
let month = date1.getMonth();
document.write("<br> Month: "+  month);

// Getting day
let day = date1.getDate();
document.write("<br> Day: "+  day);

Year: 2018 Month: 11 Day: 25

JavaScript Date Object Methods

JavaScript provides a rich set of built-in methods which are both static and instance methods that can be used to get different information from a JavaScript Date object.

MethodDescription
Date.now()Returns the number of milliseconds(Unix timestamp) for the current date and time.
Date.parse()Parses a string value of date and returns the number of milliseconds since 1 January 1970, 00:00:00 UTC, with leap seconds ignored.
Date.UTC()This function takes 7 parameters with numeric values but creates the date in UTC timezone.
setDate()sets the date of the month that ranges from 1 to 31.
setHours()set hours that range from 0 to 23
getSeconds()returns the seconds that range from 0 to 59
toDateString()converts a date value into a string
valueOf()returns the primitive value of Date object.
setMinutes()set minutes that range from 0 to 59.
setMonth()set numerical equivalence of month range from 0 to 11
setMilliseconds()set the milliseconds that range from 0 to 999
toTimeString()converts time into a string.
getDate()returns the day of the month from 1 – 31
getDay()returns the day of the week from 0 – 6
getFullYear()returns the year (4 digits for 4-digit years) of the specified date
getMinutes()returns the minutes (059) in the specified date
getMonth()returns the month (011) in the specified date
getHours()returns the hours that that range from 0 to 23.
<html>
    <head>
        <title>
            Working with Date object
        </title>
    </head>
    <body>
        <script type="text/javaScript">
            var mydate = new Date();
            document.write("Today date is: " + mydate.getDate()+"/"+(mydate.getMonth()+1)+"/"+mydate.getFullYear()+"<br/>");
            document.write("The time is: " + mydate.getHours()+":"+mydate.getMinutes()+":"+mydate.getSeconds()+"<br/>");
        </script>
    </body>
</html>

Finding the difference between JavaScript Date – Elapsed Time

We can simply subtract two dates to find the difference between any two dates. Let’s take an example to see this:

// Using Date objects
let start = Date.now();

// Do something for some time

// get the end time
let end = Date.now();
// time elapsed
let elapsed = end - start;   // elapsed time in milliseconds

But it’s not that simple as a Date object has a day, month, year, hour, minute and second values, hence we should take care while finding the elapsed time.

JavaScript Math Object

In JavaScript, Math is a built-in object which includes properties and methods for mathematical operations. We can use the Math object to perform simple and complex arithmetic operations.

Note: Math works with the JavaScript Number type only.

In Math object, All the properties and methods are static. So, we don’t need to create its object to use its property or method. Also, even if we want, we cannot create an object as Math is not a constructor function.

Using JavaScript Math

Suppose, we want to get the value of PI for geometric calculation or the square root of a number in our program then we can use Math object. Let’s see how:

let pi = Math.PI;
document.write(pi + "<br/>");

let sqrt = Math.sqrt(9);
document.write(sqrt);

3.141592653589793 3

JavaScript provides a rich set of Math properties that can be used to get predefined constant values.

JavaScript Math Properties

Following are the properties provided by the JavaScript Math object:

PropertyDescription
Eholds Euler number whose value is 2.718(approx)
LN2holds a natural logarithm of 2 whose value is 0.693(approx).
LN10holds a natural logarithm of 10, whose value is 2.302(approx).
LOG2Eholds the base-2 logarithm of E have value1.442(approx)
LOG10Eholds the base-10 logarithm of E having value 0.434(approx)
PIholds the numerical value of PI, whose approx value is 3.142
SQRT1_2holds the square root of 1/2, whose approx value is 0.707
SQRT2holds the square root of 2, having approx value 1.414

Let’s take an example to see how we can use these properties.

var e  = Math.E
document.write(e +"<br>")

var ln2  = Math.LN2
document.write(ln2 +"<br>")

var ln10  = Math.LN10
document.write(ln10 +"<br>")

var sq = Math.SQRT1_2
document.write(sq +"<br>")

2.718281828459045 0.6931471805599453 2.302585092994046 0.7071067811865476

Find Minimum and Maximum Number

Suppose, we want to find min and max numeric value from the random number of list then it can be very easy by using Math object. See the below example.

// Find minimum number
var min = Math.min(10,25,47,23,18,8,21,30)
document.write(min +"<br>")

// Find maximum number
var max = Math.max(10,25,47,23,18,8,21,30)
document.write(max +"<br>")

8 47

JavaScript Math Methods

JavaScript Math Object provides a rich set of methods that are used to make math calculation easy and helps to reduce effort and time in math-oriented programming. Here we have listed the most commonly used Math object methods:

MethodDescription
abs(x)returns the absolute value of x
ceil(x)rounds up x to a nearest biggest integer
cos(x)returns the cosine value of x
exp(x)returns the value of the exponent.
random()returns a random number between 0 and 1
tan(x)returns the tangent value of x
sqrt(x)returns the square root of x
sin(x)returns the sine value of x.
floor(x)rounds up x to the nearest smallest integer.
max(x,y,z,......n)returns the highest number from the lsit.
min(x,y,z,.......n)returns the lowest number from the list.
pow(x,y)returns x to the power of y
cos(x)returns the cosine value of x
log(x)returns the logarithmic value of x
<html>
    <head>
        <title>
            Using Math Functions
        </title>
    </head>
    <body>
        <script type="text/javaScript">
            document.write("Floor :"+Math.floor(12.7)+"<BR/>");
            document.write("Log :"+Math.log(12.7)+"<BR/>");
            document.write("Max :"+Math.max(12.7,11,25,67)+"<BR/>");
            document.write("Min :"+Math.min(3,78,90,12.7)+"<BR/>");
            document.write("pow :"+Math.pow(10,2)+"<BR/>");
            document.write("Random :"+Math.random()+"<BR/>");
            document.write("Round :"+Math.round(12.7)+"<BR/>");
            document.write("Sin:"+Math.sin(45)+"<BR/>");
            document.write("Sqrt :"+Math.sqrt(12.7)+"<BR/>");
            document.write("Exp:"+Math.exp(10)+"<BR/>");
            document.write("Tan:"+Math.tan(45)+"<BR/>");
            
        </script>
    </body>
</html>

So to use Math object properties or methods, we do not have to create an object using the new keyword, and we can directly use the properties and methods in our code.

JavaScript Number Object

JavaScript Number is a built-in wrapper object which is used to work with numerical values. A Number object can be created using the Number() constructor.

All numbers are 64 bit(8 bytes) floating-point numbers. Unlike C or C++, there are no data types like integerfloat, etc, to define numbers in JavaScript(recently with ECMAScript2016, JavaScript has started supporting BigInt type for integers).

Creating JavaScript Number Object

If we use the Number() constructor with the new keyword we can create the Number object.

let num = new Number(SOME_NUMERIC_VALUE);

and if we use the Number() function (in a non-constructor context) without the new keyword, it will create a primitive number type, which can also be used for type conversion.

Let’s take an example,

let x = new Number(290.78);
document.write(x + "<br/>");
document.write(typeof x + "<br/>");

290.78 object

Since Number is a built-in object then it has some properties and methods to work on numerical type.

JavaScript Number Object Properties

Following are the properties for the Number object:

PropertyDescription
Number.EPSILONThe smallest interval between two representable numbers.
Number.MAX_SAFE_INTEGERReturns the maximum possible safe integer value in JavaScript which is 253 – 1
Number.MAX_VALUEReturns the largest positive representable number
Number.MIN_SAFE_INTEGERReturns the minimum possible safe integer value in JavaScript which is -(253 – 1)
Number.MIN_VALUEReturn the minimum representable numerical value possible in JavaScript.
Number.NaNIt represents the special “Not a Number” value
Number.NEGATIVE_INFINITYIt represents the value of Negative Infinity.
Number.POSITIVE_INFINITYIt represents the value of Negative Infinity.
Number.prototypeThis can be used to add more properties to the Number object

NOTE: Any value larger than the MAX_SAFE_INTEGER value will get corrupted when processed in JavaScript.

Let’s take an example to see some of these properties in action.

// Range of Number
document.write(Number.MIN_VALUE+"<br>")
document.write(Number.MAX_VALUE+"<br>")
document.write(Number.NEGATIVE_INFINITY+"<br>")
document.write(Number.POSITIVE_INFINITY+"<br>")
document.write(Number.prototype+"<br>")
document.write(Number.MIN_SAFE_INTEGER+"<br>")
document.write(Number.MAX_SAFE_INTEGER+"<br>")

5e-324 1.7976931348623157e+308 -Infinity Infinity 0 -9007199254740991 9007199254740991

JavaScript Number Object Methods

JavaScript Number object has both static methods(used without any Number object created) and instance methods(used on the object). Following are the most commonly used methods of the Number object:

Method nameDescription
Number.isNaN()Static method; used to check whether the given value is NaN or not.
Number.isFinite()Static method; used to check whether the given value is a finite number or not.
Number.isInteger()Static method; used to check whether the given value is an integer number or not.
Number.isSafeInteger()Static method; used to check if the given value is a safe value or not, i.e. between 253 – 1 to -(253 – 1)
Number.parseFloat(string)Static method; used to convert a string to a floating-point number.
Number.parseInt(string, [radix])Static method; used to convert a string to an integer. Here radix represents the base in mathematical numeral systems.
valueOf()Returns the primitive value of the Number object.
toString()Returns a String value of number object.
toFixed(x)Rounds up a number to x digits after the decimal.
toPrecision(x)Rounds up a number to a length of x digits.
toExponential(x)Converts a number into an Exponential notation.

Let’s take a few examples to see some of these functions in action.

Convert Number Object to Primitive

The Number object provides a method valueOf() which can be used to convert the Number object to a primitive type.

let x = new Number(290.78);
document.write(typeof x + "<br/>");

// Conversion from object to number
let num = x.valueOf()
document.write(typeof num + "<br/>");

object number

Using Number in Non-Constructor Context

As we mentioned in the beginning that if we use Number function without the new keyword, we can use it for type conversion. So let’s see a few examples for it:

// using the Date object
let d = new Date('December 17, 1995 03:24:00');
console.log(Number(d));    // Logs: 819199440000

The above code will give output 819199440000 which is the UNIX timestamp equivalent of the date specified. So the date is successfully converted into a number.

Also, we can use the Number function for simpler conversions like below:

Number('77');        // 77
Number('70.7');      // 70.7
Number('');          // 0
Number('foo');       // NaN
Number('-Infinity'); // -Infinity
Number(null);        // 0

JavaScript Number Object Example

In this example, we are using Built-in methods to understand their uses.

<html>
    <head>
        <title>Using Number Object</title>
    </head>
    <body>
        <script type="text/javaScript">
            let num = new Number('18.907');
            document.write(num.toExponential() +"<br/>");
            document.write(num.toFixed() +"<br/>");
            document.write(num.toPrecision(3) +"<br/>");
            document.write(typeof num.toString() +"<br/>");
            document.write(num.valueOf() +"<br/>");
        </script>
    </body>
</html>

You can use the Number object for checking the type of any value, for example, if you have to verify if a given value is a number or not, you can use the Number.isNaN method. Similarly, you can also use the Number object properties to assign MAX and MIN allowed value in your script.