0% found this document useful (0 votes)
2 views

JavaScript Objects (1)

This document provides a comprehensive overview of JavaScript objects, including how to create them using object literals and the Object() constructor, as well as how to access their properties and methods. It also covers the JavaScript Date object, detailing how to create, convert, and compare dates, along with various date methods available. Key points include the ability to nest objects, pass them by reference, and utilize different date formats.

Uploaded by

Shub P
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaScript Objects (1)

This document provides a comprehensive overview of JavaScript objects, including how to create them using object literals and the Object() constructor, as well as how to access their properties and methods. It also covers the JavaScript Date object, detailing how to create, convert, and compare dates, along with various date methods available. Key points include the ability to nest objects, pass them by reference, and utilize different date formats.

Uploaded by

Shub P
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

JavaScript Objects: Create Objects,

Access Properties & Methods


Here you will learn objects, object literals, Object() constructor function, and
access object in JavaScript.

You learned about primitive and structured data types in JavaScript. An object
is a non-primitive, structured data type in JavaScript. Objects are same as
variables in JavaScript, the only difference is that an object holds multiple
values in terms of properties and methods.

In JavaScript, an object can be created in two ways: 1) using Object


Literal/Initializer Syntax 2) using the Object() Constructor function with
the new keyword. Objects created using any of these methods are the same.

The following example demonstrates creating objects using both ways.

Example: JavaScript Objects


var p1 = { name:"Steve" }; // object literal syntax
var p2 = new Object(); // Object() constructor function
p2.name = "Steve"; // property

Above, p1 and p2 are the names of objects. Objects can be declared same
as variables using var or let keywords. The p1 object is created using the
object literal syntax (a short form of creating objects) with a property
named name. The p2 object is created by calling the Object() constructor
function with the new keyword. The p2.name = "Steve"; attach a
property name to p2 object with a string value "Steve".

Create Object using Object Literal Syntax


The object literal is a short form of creating an object. Define an object in
the { } brackets with key:value pairs separated by a comma. The key would be
the name of the property and the value will be a literal value or a function.

Syntax:
var <object-name> = { key1: value1, key2: value2,...};

The following example demonstrates objects created using object literal syntax.

Example: Object Literal Syntax


var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single method
var message = {
showMessage: function (val)
{
alert(val);
}
};
// object with properties & method
var person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function ()
{
return this.firstName + ' ' + this.lastName
}
};

Note that the whole key-value pair must be declared. Declaring only a key
without a value is invalid, as shown below.

Example: Wrong Syntax


var person = { firstName };
var person = { getFullName: };

Create Objects using Objects() Constructor


Another way of creating objects is using the Object() constructor function
using the new keyword. Properties and methods can be declared using the dot
notation .property-name or using the square brackets ["property-name"], as
shown below.

Example: Create Object using Object() Constructor


var person = new Object();
// Attach properties and methods to person object
person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

An object can have variables as properties or can have computed properties, as


shown below.

Example: Variables as Object Properties


var firstName = "James";var lastName = "Bond";
var person = { firstName, lastName }

Access JavaScript Object Properties &


Methods
An object's properties can be accessed using the dot notation obj.property-
name or the square brackets obj["property-name"]. However, method can be
invoked only using the dot notation with the parenthesis, obj.method-name(),
as shown below.

Example: Access JS Object


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
person.firstName; // returns James
person.lastName; // returns Bond

person["firstName"];// returns James


person["lastName"];// returns Bond

person.getFullName(); // calling getFullName function

In the above example, the person.firstName access the firstName property of


a person object. The person["firstName"] is another way of accessing a
property. An object's methods can be called using () operator
e.g. person.getFullName(). JavaScript engine will return the function definition
if accessed method without the parenthesis.

Accessing undeclared properties of an object will return undefined. If you are


not sure whether an object has a particular property or not, then use
the hasOwnProperty() method before accessing them, as shown below.

Example: hasOwnProperty()
var person = new Object();

person.firstName; // returns undefined


if(person.hasOwnProperty("firstName")){
person.firstName;
}

The properties and methods will be available only to an object where they are
declared.

Example: Object Constructor


var p1 = new Object();
p1.firstName = "James";
p1.lastName = "Bond";
var p2 = new Object();
p2.firstName; // undefined
p2.lastName; // undefined
p3 = p1; // assigns object
p3.firstName; // James
p3.lastName; // Bond
p3.firstName = "Sachin"; // assigns new value
p3.lastName = "Tendulkar"; // assigns new value

Enumerate Object's Properties


Use the for in loop to enumerate an object, as shown below.

Example: Access Object Keys


var person = new Object();
person.firstName = "James";
person.lastName = "Bond";
for(var prop in person){
alert(prop); // access property name
alert(person[prop]); // access property value
};
Pass by Reference
Object in JavaScript passes by reference from one function to another.

Example: JS Object Passes by Reference


function changeFirstName(per)
{
per.firstName = "Steve";
}
var person = { firstName : "Bill" };

changeFirstName(person)

person.firstName; // returns Steve

Nested Objects
An object can be a property of another object. It is called a nested object.

Example: Nested JS Objects


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
address: {
id: 1,
country:"UK"
}
};

person.address.country; // returns "UK"

Points to Remember :

. JavaScript object is a standalone entity that holds multiple values in terms of


properties and methods.
. Object property stores a literal value and method represents function.
. An object can be created using object literal or object constructor syntax.
. Object literal:
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

Object constructor:
var person = new Object();

person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

Object properties and methods can be accessed using dot notation or [ ] bracket.

An object is passed by reference from one function to another.

An object can include another object as a property.

JavaScript Date: Create, Convert,


Compare Dates in JavaScript
JavaScript provides Date object to work with date & time, including days, months,
years, hours, minutes, seconds, and milliseconds.

Use the Date() function to get the string representation of the current date and
time in JavaScript. Use the new keyword in JavaScript to get the Date object.

Example: Date In JavaScript

Date(); //Returns current date and time string


//or
var currentDate = new Date(); //returns date object of current date and
time

Create a date object by specifying different parameters in


the Date() constructor function.

Date() Syntax
new Date()new Date(value)new Date(dateString)new Date(year,
monthIndex)new Date(year, monthIndex, day)new Date(year, monthIndex,
day, hours)new Date(year, monthIndex, day, hours, minutes)new Date(year,
monthIndex, day, hours, minutes, seconds)new Date(year, monthIndex, day,
hours, minutes, seconds, milliseconds)

Parameters:

 No Parameters: A date object will be set to the current date & time if no
parameter is specified in the constructor.
 value: An integer value representing the number of milliseconds since
January 1, 1970, 00:00:00 UTC.
 dateString: A string value that will be parsed using Date.parse() method.
 year: An integer value to represent a year of a date. Numbers from 0 to 99
map to the years 1900 to 1999. All others are actual years.
 monthIndex: An integer value to represent a month of a date. It starts
with 0 for January till 11 for December
 day: An integer value to represent day of the month.
 hours: An integer value to represent the hour of a day between 0 to 23.
 minutes: An integer value to represent the minute of a time segment.
 seconds: An integer value to represent the second of a time segment.
 milliseconds: An integer value to represent the millisecond of a time
segment. Specify numeric milliseconds in the constructor to get the date
and time elapsed from 1/1/1970.

In the following example, a date object is created by passing milliseconds in


the Date() constructor function. So date will be calculated based on
milliseconds elapsed from 1/1/1970.

Example: Create Date by Specifying Milliseconds


var date1 = new Date(0); // Thu Jan 01 1970 05:30:00
var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01
var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05

The following example shows various formats of a date string that can be
specified in a Date() constructor.

Example: Create Date by Specifying Date String


var date1 = new Date("3 march 2015");
var date2 = new Date("3 February, 2015");
var date3 = new Date("3rd February, 2015"); // invalid date
var date4 = new Date("2015 3 February");
var date5 = new Date("3 2015 February ");
var date6 = new Date("February 3 2015");
var date7 = new Date("February 2015 3");
var date8 = new Date("2 3 2015");
var date9 = new Date("3 march 2015 20:21:44");

You can use any valid separator in the date string to differentiate date
segments.

Example: Create Date using Different Date Separator


var date1 = new Date("February 2015-3");
var date2 = new Date("February-2015-3");
var date3 = new Date("February-2015-3");
var date4 = new Date("February,2015-3");
var date5 = new Date("February,2015,3");
var date6 = new Date("February*2015,3");
var date7 = new Date("February$2015$3");
var date8 = new Date("3-2-2015"); // MM-dd-YYYY
var date9 = new Date("3/2/2015"); // MM-dd-YYYY

Specify seven numeric values to create a date object with the specified year,
month and optionally date, hours, minutes, seconds and milliseconds.

Example: Date
var date1 = new Date(2021, 2, 3); // Mon Feb 03 2021 var date2 = new
Date(2021, 2, 3, 10); // Mon Feb 03 2021 10:00 var date3 = new
Date(2021, 2, 3, 10, 30); // Mon Feb 03 2021 10:30 var date4 = new
Date(2021, 2, 3, 10, 30, 50); // Mon Feb 03 2021 10:30:50 var date5 =
new Date(2021, 2, 3, 10, 30, 50, 800); // Mon Feb 03 2021 10:30:50

Date Formats
JavaScript supports ISO 8601 date format by default - YYYY-MM-
DDTHH:mm:ss.sssZ

Example: ISO Date Format


var dt = new Date('2015-02-10T10:12:50.5000z');

Convert Date Formats


Use different Date methods to convert a date from one format to another
format, e.g., to Universal Time, GMT, or local time format.

The following example


demonstrates ToUTCString(), ToGMTString(), ToLocalDateString(),
and ToTimeString() methods to convert date into respective formats.

Example: Date Conversion in Different Formats


var date = new Date('2015-02-10T10:12:50.5000z');

date; 'Default format:'

date.toDateString();'Tue Feb 10 2015'

date.toLocaleDateString();'2/10/2015'

date.toGMTString(); 'GMT format'

date.toISOString(); '2015-02-10T10:12:50.500Z'

date.toLocaleString();'Local date Format '

date.toLocaleTimeString(); 'Locale time format '

date.toString('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'

date.toTimeString(); '15:42:50'

date.toUTCString(); 'UTC format '

To get date string in formats other than the ones listed above, you need to
manually form the date string using different date object methods. The
following example converts a date string to DD-MM-YYYY format.

Example: Get Date Segments


var date = new Date('4-1-2015'); // M-D-YYYY
var d = date.getDate();var m = date.getMonth() + 1;var y =
date.getFullYear();
var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) +
'-' + y;

Note:
Use third party JavaScript Date library like datejs.com or momentjs.com to work with
Dates extensively in JavaScript.

Compare Dates in JavaScript


Use comparison operators to compare two date objects.
Example: Date Comparison
var date1 = new Date('4-1-2015');var date2 = new Date('4-2-2015');
if (date1 > date2)
alert(date1 + ' is greater than ' + date2);else (date1 < date2 )
alert(date1 + ' is less than ' + date2);

Date Methods Reference


The following table lists all the get methods of Date object.

Method Description
getDate() Returns numeric day (1 - 31) of the specified date.
getDay() Returns the day of the week (0 - 6) for the specified date.
getFullYear() Returns four digit year of the specified date.
getHours() Returns the hour (0 - 23) in the specified date.
getMilliseconds() Returns the milliseconds (0 - 999) in the specified date.
getMinutes() Returns the minutes (0 - 59) in the specified date.
getMonth() Returns the month (0 - 11) in the specified date.
getSeconds() Returns the seconds (0 - 59) in the specified date.
getTime() Returns the milliseconds as number since January 1, 1970, 00:00:00 UTC.
getTimezoneOffset() Returns the time zone offset in minutes for the current locale.
getUTCDate() Returns the day (1 - 31) of the month of the specified date as per UTC time zone.
getUTCDay() Returns the day (0 - 6) of the week of the specified date as per UTC timezone.
getUTCFullYear() Returns the four digits year of the specified date as per UTC time zone.
getUTCHours() Returns the hours (0 - 23) of the specified date as per UTC time zone.
getUTCMilliseconds() Returns the milliseconds (0 - 999) of the specified date as per UTC time zone.
getUTCMinutes() Returns the minutes (0 - 59) of the specified date as per UTC time zone.
getUTCMonth() Returns the month (0 - 11) of the specified date as per UTC time zone.
getUTCSeconds() Returns the seconds (0 - 59) of the specified date as per UTC time zone.
getYear() Returns the no of years of the specified date since 1990. This method is Deprecated

The following table lists all the set methods of Date object.

Method Description
setDate() Sets the day as number in the date object.
setFullYear() Sets the four digit full year as number in the date object. Optionally set month and date.
setHours() Sets the hours as number in the date object. Optionally set minutes, seconds and milliseconds.
setMilliseconds() Sets the milliseconds as number in the date object.
setMinutes() Sets the minutes as number in the date object. Optionally set seconds & milliseconds.
setMonth() Sets the month as number in the date object. Optionally set date.
setSeconds() Sets the seconds as number in the date object. Optionally set milliseconds.
setTime() Sets the time as number in the Date object since January 1, 1970, 00:00:00 UTC.
setUTCDate() Sets the day in the date object as per UTC time zone.
setUTCFullYear() Sets the full year in the date object as per UTC time zone
setUTCHours() Sets the hour in the date object as per UTC time zone
setUTCMilliseconds() Sets the milliseconds in the date object as per UTC time zone
setUTCMinutes() Sets the minutes in the date object as per UTC time zone
setUTCMonth() Sets the month in the date object as per UTC time zone
setUTCSeconds() Sets the seconds in the date object as per UTC time zone
setYear() Sets the year in the date object. This method is Deprecated
toDateString() Returns the date segment from the specified date, excludes time.
toGMTString() Returns a date string in GMT time zone.
toLocaleDateString() Returns the date segment of the specified date using the current locale.
toLocaleFormat() Returns a date string in default format.
toLocaleString() Returns a date string using a current locale format.
toLocaleTimeString() Returns the time segment of the specified Date as a string.
toString() Returns a string for the specified Date object.
toTimeString() Returns the time segment as a string from the specified date object.
toDateString() Returns the date segment from the specified date, excludes time.
toUTCString() Returns a string as per UTC time zone.
valueOf() Returns the primitive value of a Date object.

You might also like