Objects In JavaScript For Beginners

Objects in javascript

 
JavaScript is an "object-based language". In this scripting, there is no such term as "class".
 
-->Create object
  1. var mobilePhone = new Object();  
The above line creates the empty object & Object() is called as constructor.
  1. var mobilePhone = {};  
The above line also creates the empty object.
 
Find the results of the above lines in the below snippet,
 
Objects In JavaScript
 
Assigning members to the Object
 
Objects in JavaScript will be in the form of key-value pairs.
 
We can assign any type of value to the JavaScript without any restriction.
 
For example,
  1. var mobilePhone = new Object();  
  2. mobilePhone.Name = "Nokia";  
  3. mobilePhone.Model = "N-1234"  
  4. mobilePhone.Ram = "3 GB"  
  5. mobilePhone.IsCameraExists = true;  
  6. mobilePhone.Cost = 3000;  
In the above lines of code I have created the properties like Name, Model, Ram, IsCameraExists and Cost and also assigned the values to them. Now, the mobilePhone object is having 5 properties.
 
Accessing the object members
 
Now, if I try to access the mobilePhone.Name in the console, it will print "Nokia" as a result.
 
For more observe the below image,
 
Objects In JavaScript 
 
We can also assign the properties while creating the object as shown below,
  1. var mobilePhone = {"Name":"Nokia","Model":"N-1234","Ram":"3 GB","Iscamera" : true,"cost":3000}  
And in any case,  the way of accessing will be the same as mentioned above.
 
mobilePhone.Name --> Returns "Nokia".
 
For more, observe the below image,
 
Objects In JavaScript 
 
Note 1
 
We can also access the object members in the following way too.
 
mobilePhone["Name"] --> Results "Nokia"
 
Note 2
 
If we try to access an unknown property or member by using the object it returns the "undefined".
 
Ex - mobilePhone.abc --> returns "undefined"
 
Functions in Object
 
In JavaScript for an object, we are allowed to use a function as a member. Whenever we add a property, we can access the function also.
 
Ex,
  1. mobilePhone.MakeCall = function() {  
  2.     alert('Hello, making a call..')  
  3. }  
In the above line, I'm creating a member "MakeCall" for a mobilePhone object and for this member I had assigned the anonymous function with some logic.
 
Observe the below image for clarity
 
Objects In JavaScript