In this guide, we will look into Javascript object basics, properties, creating objects, creating methods, accessor methods(getters/setters), etc.
In real life, a car is an object. A car has properties like weight and color, and methods like start and stop. Let's demonstrates this by creating a Javascript object:
To understand and best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example, and run it by pressing the Enter/Return key.
1. JavaScript Object Properties
Properties are the most important part of any JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read-only.
Accessing JavaScript Properties
The syntax for accessing the property of an object is:
objectName.property
or
objectName["property"]
or
objectName[expression]
Let's create a user object with few properties:
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29
}
Example 1:
let firstName = user.firstName; // objectName.property
console.log(firstName);
Example 2:
var lastName = user['lastName']; // objectName["property"]
console.log(lastName);
Example 3:
let x = "emailId";
var emailId = user[x]; // objectName[expression]
console.log(emailId);
Adding New Properties
You can add new properties to an existing object by simply giving it a value. Example: Let's create a user object with few properties and add new fullName property to an existing user object.
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29
}
user.fullName = user.firstName + " " + user.lastName;
console.log(user.fullName);
Output:
Ramesh Fadatare
Deleting Properties
The delete keyword deletes a property from an object:
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29
}
delete user.age;
console.log(user);
Output:
{firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh@gmail.com"}
Enumerate the properties of an object
Starting with ECMAScript 5, there are three native ways to list/traverse object properties:
- for...in loops - This method traverses all enumerable properties of an object and its prototype chain
- Object.keys(o) - This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.
- Object.getOwnPropertyNames(o) - This method returns an array containing all own properties' names (enumerable or not) of an object o.
Example 1: The for...in statement iterates over all non-Symbol, enumerable properties of an object.
var txt = "";
var person = {fname:"Ramesh", lname:"Fadatare", age:29};
var x;
for (x in person) {
txt += person[x] + " ";
}
Output:
"Ramesh Fadatare 29 "
Example 2: The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
Output:
["a", "b", "c"]
Example 3: The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
Output:
["a", "b", "c"]
2. Creating new objects
There are several ways to create objects in Javascript. Let's discuss four different ways to create an object in javascript with examples.
2.1. Using object literals or object initializers
Using object literals is the simplest way to create an object in Javascript. An object literal also called an object initializer, is a comma-separated set of paired names and values.
Let's create a Javascript object using an object literal:
// using Object Literals
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
console.log(JSON.stringify(user));
console.log(user.getFullName());
// access object properties
console.log('firstName :', user.firstName);
console.log('lastName :', user.lastName);
console.log('emailId :', user.emailId);
console.log('age :', user.age);
Output:
{"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}
Ramesh Fadatare
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
2.2. Using a constructor function
The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object.
Below two steps define and create an object:
- Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
- Create an instance of the object with a new keyword.
// using constructor function
function User(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
}
var user1 = new User('Ramesh', 'Fadatare', 'ramesh24@gmail.com', 29);
var user2 = new User('John', 'Cena', 'john@gmail.com', 45);
var user3 = new User('Tony', 'Stark', 'tony@gmail.com', 52);
console.log(user1);
console.log(user2);
console.log(user3);
Output:
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh24@gmail.com", age: 29}
User {firstName: "John", lastName: "Cena", emailId: "john@gmail.com", age: 45}
User {firstName: "Tony", lastName: "Stark", emailId: "tony@gmail.com", age: 52}
2.3. Using the Object.create() method
Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.
// using Object.create Method
var Employee = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
var employee1 = Object.create(Employee);
// access object properties
console.log('firstName :', employee1.firstName);
console.log('lastName :', employee1.lastName);
console.log('emailId :', employee1.emailId);
console.log('age :', employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
More examples:
// Animal properties and method encapsulation
var Animal = {
type: 'Invertebrates', // Default value of properties
displayType: function() { // Method which will display type of Animal
console.log(this.type);
}
};
// Create new animal type called animal1
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType(); // Output:Fishes
2.4. Using ES 6 Class
ECMAScript 6 introduced the class keyword to create classes in JavaScript. Now you can use the class attribute to create a class in JavaScript instead of a function constructor, and use the new operator to create an instance.
Example: Let's create Employee class:
class Employee {
constructor(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
}
getFullName(){
return this.firstName + " " + this.lastName;
}
getFirstName(){
return this.firstName;
}
}
Now, we create an object of Employee class and access its methods:
const employee = new Employee('Ramesh', 'Fadatare', 'ramesh@gmail.com', 29);
console.log(employee.getFirstName());
console.log(employee.getFullName());
Let's create more examples of Javascript classes:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
3.JavaScript Object Methods
JavaScript methods are actions that can be performed on objects. For example, below user object defined getFullName() methods which returns combination of firstName and lastName:
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return this.firstName + " " + this.lastName;
}
}
console.log(JSON.stringify(user));
console.log(user.getFullName());
Output:
{"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}
Ramesh Fadatare
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
Example:
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
console.log(user.getFullName());
Output:
Ramesh Fadatare
Using Built-In Methods
This example uses the toUpperCase() method of the String object, to convert a text to uppercase:
var message = "Hello world!";
var x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
Adding a Method to an Object
Adding a new method to an object is easy:
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
user.getFirstName = function(){
return this.firstName;
}
console.log(user.getFirstName());
Output:
Ramesh
4. JavaScript Accessors (Getters and Setters)
ECMAScript 5 (2009) introduced Getter and Setters.
Getters and setters allow you to define Object Accessors (Computed Properties).
4.1 JavaScript Getter (The get Keyword)
This example uses a lang property to get the value of the language property.
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};
console.log(person.lang);
Output:
en
JavaScript Setter (The set Keyword)
This example uses a lang property to set the value of the language property.
var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
console.log(person.language);
Output:
en
Check out all Javascript articles at JavaScript Tutorial Series.
Comments
Post a Comment
Leave Comment