Objects
Objects in JavaScript is used for two purpose.
- Objects are used as the associative array. Which has the key and value pairs.
- Objects are used for object-oriented programming.
Objects As Associative Array
Creating objects
We can create an empty object in two way. Both the way are doing the same thing, they simply create the empty object.
var obj = new Object(); //or var obj = {};
Object store the values by key which we can assign or delete using “dot notation“.
We can access and manipulate the value of the object using the it’s key. we can access the key from the object in the two way.
- Dot notation.
- Using square brackets, The key is passed as the string.
var objDetails = {}; objDetails.FirstName = "James"; // Assign new key "FirstName" using dot notation objDetails["LastName"] = "Bond"; // Assign new key "LastName" using square brackets alert("Hello, Mr. " + objDetails["FirstName"] + " " + objDetails.LastName); // Access the value by key delete objDetails.FirstName; delete objDetails["LastName"]; // Delete the key and it's value using the delete statement.
As you seen in above example, First I create the object, after that I add the two new keys into the object in two different ways.
In first way I use the dot notation to create the property inside the object, and In second way I used the square brackets to insert the another property inside the object.
After that I access that property, in same way using the dot notation and square brackets, and at the last I delete that both property from the object.
So we can use both the dot notation and square brackets for the creating the property and manipulate the property.
There is no much more difference between the square brackets and dot notation.
- In dot notation, We can directly uses the property name with the object without any quote.
- In square brackets we have to pass the property name in the quote or we must be have to pass the any variable, so the object return the key named by value of the variable.
var objDetails = { FirstName: "James" }; var key = "FirstName"; alert(objDetails[key]); // James // Access the value using the square brackets alert(objDetails.FirstName); // James // Access the value using the dot notation
Object creation with Property
We can also add the as many as properties we want, while creating the new object. Yes we are able to add the property while creating the object. We have to use the curly-brackets {}, and have to pass the key-value pairs list inside the curly-brackets.
var objUser = { Id: 13, FirstName: "James", LastName: "Bond", Location: "USA", BirthDate: "13/05/1969" }; // It is the same as.... var objUser = {}; objUser.Id = 13; objUser.FirstName = "James"; objUser.LastName = "Bond"; objUser.Location = "USA"; objUser.BirthDate = "13/05/1969";
But the first one is much more readable than the second one.
Nested Objects
We can also able to create the object inside the other object called nested object.
var objShape = { area: 0, size: { width: 5, height: 100 } }; objShape.area = objShape.size.width * objShape.size.height; alert(objShape.area); // 500
Non-existing properties
We are able to get any property from the object that may be exist or not in the object.
If property exist than it return the value of it, If the property does not exist than it return the undefined. But it does not throw the error.
var obj = {}; alert(obj.FirstName); //undefined
Checking key is exist in the object
We can also check the specific key is exist in the object or not.
We have to check the property with the undefined statement. If the key is not exist than the property value will be same to undefined otherwise not.
var obj = {}; if (obj.FirstName === undefined) { alert("Property is not exist!!!"); } else { alert("Property is exist!!!"); }
But there is issue while checking the property is exist or not with the undefined statement. Because the object may be have the key with the value undefined.
var obj = { Key: undefined }; alert(obj.Key === undefined); //true
So the solution is to check the property is exist or not in the object with the in keyword.
var obj = { FirstName: undefined }; alert("FirstName" in obj); //true alert("LastName" in obj); //false
So in above example, one object is created with the key FirstName and the value is undefined. If we check the key is exist or not with the === operator than it will return the true. It means the property is does not exist. But the property is exist and have the value undefined.
So in keyword help us to check the property is exist or not in the object, If the property is exist than it will return the true, if not exist than it will return the false.
So when I check the FirstName property with the in keyword, than it return the true. It means property is exist in the object. As well as I checked that LastName property with the in keyword and it return the false, Means the property is not exist.
Let’s check above example with the === operator.
var obj = { FirstName: undefined }; alert(obj.FirstName === undefined); //true alert(obj.LastName === undefined); //true
In above example, Both time === operator return true, it means the both property does not exist in the object but the FirstName property is exist.
So it recommend to the use the in keyword to check the property is exist or not.
Iterating over keys-values
We can also get all the keys from the object one by one using the for…in loop.
var obj = { FirstName: "James", LastName: "Bond" }; for (var key in obj) { alert("Key is: " + key + " and value is: " + obj[key]); } //Key is: FirstName and value is: James //Key is: LastName and value is: Bond
Order of iteration:
It may be vary by browser, different different browser may be store the keys in the different different order.
But in generally, many browser follow the following common rules:
- It will store the keys in the ascending numeric order.
- After it will store the keys in the alphabetical order.
var obj = { FirstName: "James", LastName: "Bond", 1: "1", "1A": "1" }; for (var key in obj) { alert("Key is: " + key + " and value is: " + obj[key]); } //Key is: 1 and value is: 1 //Key is: FirstName and value is: James //Key is: LastName and value is: Bond //Key is: 1A and value is: 1
References in JavaScript Object
In JavaScript if we assign the object to the any variable. If that variable change the any property of the object, than the change will be reflect to the main object as well as to another variable, which get the references from that variable.
var obj = { i: 1 }; var obj1 = obj; var obj2 = obj; var obj3 = obj; obj1.i = 2; alert(obj.i); //2 alert(obj2.i); //2 alert(obj3.i); //2
As you seen in above example, First I assign the value of the obj object to the variable obj1, obj2 and obj3 and after that I change the value of the obj1’s property i to 2. So it will reflect the main obj object and also the obj2 and obj3 variable.
It happen because, when we are assiging the obj object value to the obj1, JavaScript internally assign the memory pointer to the variable obj1. So when we change the value of the obj1 than it change the value of the obj.
If we passed the object to the function as the parameter, and that function change the property of the object, than it also reflect the property of the main object.
function add(object) { object.i += 1; } var obj = { i: 0 }; for (var k = 1; k <= 5; k++) { add(obj); } alert(obj.i); //5
As you know the object is always the passed by references in default. So when the function changing the value of the object which it get as the parameter, It actually change the value of the original object.
So now the property i of the original object has the value 5.
Properties and Methods
We are also able to create the properties and method inside the object.
var Shape = { width: 0, height: 0, area: function () { //This is the area() method //inside the Shape object return this.width * this.height; } }; Shape.width = 10; Shape.height = 10; //Call the area() method //of the shape object. alert(Shape.area()); //100
Check the method is exist inside the object
var obj = { m1: function () { return "m1"; }, m2: function () { return "m2"; } }; if (obj.m1) { alert(obj.m1()); } if (typeof obj.m2 === "function") { alert(obj.m2()); }
In first if condition, I simply pass the method reference, If condition will return the true if the method is exist other wise it will return the false.
In second if condition, First I getting the typeof the m1() method using the typeof statement, it will return the string which describe the which type of the object it is. Here the m2() is function so the typeof statement will return the string “function”. Which I checked with the static “function” string.
So the both way is correct to check the method is exist or not.
Object for the object-oriented programming
Before the JavaScript ES6 JavaScript does not provide the class keyword to create the class in JavaScript. But now JavaScript ES6 have the class keyword to create the class and most of the modern browser supports the JavaScript ES6.
But before the JavaScript ES6, we have to use the function to create the class.
Another way is to create the object in JavaScript is to construct it by calling a function with new directive.
So while calling the function with the new directive, it returns the object, which have the properties and method defined in the function.
function User() { this.FirstName = ""; this.LastName = ""; this.SetName = function (fName, lName) { this.FirstName = fName; this.LastName = lName; } this.SayHello = function () { return "Hello, " + this.FirstName + " " + this.LastName; } } var obj = new User(); obj.SetName("James", "Bond"); alert(obj.SayHello()); //Hello, James Bond
So, here in above example, First I create the function which have the two properties FirstName and LastName, after that I created the two method SetName and SayHello for getting the name from the user and say the hello to the user.
When I construct the object from the function using the new directive, than the function will be return the object like this:
var User = { FirstName: "", LastName: "", SetName: function (fName, lName) { this.FirstName = fName; this.LastName = lName; }, SayHello: function () { return "Hello, " + this.FirstName + " " + this.LastName; } }
So now the obj variable have the above defined object, and we can set the any properties of the object and we can call the any method of the object.
Click here to read more about the object-oriented programming in the JavaScript.