JavaScript | Objects

In our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don’t exist in JavaScript. In this article, objects are discussed in detail.

Creating Objects

In JavaScript, Objects can be created using two different methodologies namely Literal Form and Constructed Form.

  • Literal Form: The literal form uses the construction of object literals that can be said as a collection of key-value pairs enclosed within a pair of curly braces. The syntaxial form is shown below.
    var obj = {
      key1: value1,
      key2: value2,
      ...
    };
    
  • Constructed Form: The Constructed form uses either a object constructor function or the new keyword to create an empty object ad then adds properties to the object one by one. The syntaxial forms are shown below.

    • Object Constructor Function: In this methodology the user creates an explicit function to take required values as parameters and assign them as the properties of the desired object.
      function obj(value1, value2, ...) {
          this.key1 = value1;
          this.key2 = value2;
          ...
      }
      
    • Using New Keyword: This methodology uses the New keyword in front of any constructor method or any built in constructor method ( such as Object, Date, String etc ) and creates a new instance of the following object by mounting it on memory.
      var obj = new Object();
      obj.key1 = value1;
      obj.key2 = value2;
      ...
      

Differences between using Object Literals and the Constructed Form: Both the constructed form and literal form result in creating exactly the same sort of object i.e. the end result is same for both the methodologies. The only difference between the both is that object literals can take care of several key-value pairs at once and thus is more convenient while on the other hand with the constructed-form objects, we must add the properties one-by-one in separate statements.
Note: It is highly uncommon to use the Constructed Form over the Object Literals for creating objects, hence for any further illustrations we will be using the object literals on most occasions.



Built-In Objects

JavaScript consists of a bunch of Built-In Objects, the following list explores most of them. Although these built-ins have the appearance of being actual types or classes like in any other OOP, in JavaScript these are only functions that can be used as constructors to create objects of the particular sub-type.

  • String
  • Number
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegExp
  • Error

Now let us take an example to differentiate between Objects and Primitives.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Create string primitive.
var strPrimitive = "GeeksforGeeks";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false
  
// Use the Built-in String Function as Constructor.
var strObject = new String( "GeeksforGeeks" );
typeof strObject; // "object"
strObject instanceof String; // true
  
// inspect the object sub-type
Object.prototype.toString.call( strObject ); // [object String]

chevron_right


In the above example, we saw that creating a string primitive didn’t create an object nor an instance of String. Primitives are literal and immutable value, to perform tasks like calculating the length or change any character at any position we must use the Object of type String. But JavaScript is a dynamic language and luckily for the developers, JavaScript coerces a string primitive to a String class whenever any operation needs it to be. It is to be noted, that due to internal coercion it is vastly preferred to use primitives as much as possible instead of objects.

Content of Objects

JavaScript objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. The Property Value can be of the primitive data type or an object or even a function. The property can also be globally accessible in spite of being owned by an object. The general syntax of defining an object property is as shown below,

objectName.objectProperty = propertyValue;

The following program will clear the concepts we discussed above,

filter_none

edit
close

play_arrow

link
brightness_4
code

var myObj = {
  
  // Integer Property.
  int_prop: 5,
  
  // String Property. 
  str_prop: "GeeksforGeeks",
  
  // Object Property (Date). 
  obj_prop: new Date(),
  
  // Object Property.
  inner_obj: {
    int_prop: 6   
  },
  
  // Function Property.
  func_prop: function(){
     console.log("Welcome to GeeksforGeeks!");
  }
};
  
console.log(myObj.int_prop);
console.log(myObj.str_prop);
console.log(myObj.obj_prop.toLocaleTimeString());
console.log(myObj.inner_obj.int_prop);
myObj.func_prop();

chevron_right


Output:

5
GeeksforGeeks
5:47:55 PM
6
Welcome to GeeksforGeeks!

As per conventions, functions associated with an object is known as methods. This is considered to be a small difference between a function and a method. A function is an independent sequence of a bunch of statements whereas a method is associated to an object and is generally referenced by the this keyword.

Defining Global Variables to be owned by Objects: This is mostly done on methods, the process is fairly simple we will define our function as we are used to, and while defining the function to be a member of the object properties we will just give the name of the function as the value of one key. Let us see in the example given below.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Define Function Explicitly.
function toGreet()
{
  console.log("Hello There!");
}
  
var myObj = {
  
  // Mention Function-Name as Value.
  greet: toGreet,
  
  // Define Function implicitly.
  byWhom: function(){
    console.log(" - GeeksforGeeks.org");
  }
}
  
myObj.greet();
myObj.byWhom();

chevron_right


Output:

Hello There!
 - GeeksforGeeks.org

Note: The ‘with’ keyword can be used to reference an object’s properties. The object specified as an argument to with becomes the default object for the duration of the block that follows. This is generally recommended not to be used by developers. Use of with is not allowed in JavaScript strict mode.

Important Points

  • Date values can only be created with their constructed object form, as they have no literal form.
  • Objects, Arrays, Functions, and RegExps (regular expressions) are all objects regardless of their creation methodologies i.e. whether the literal or constructed form was used to create them.
  • The constructed form may offer more customization while creation of an object, this is the sole advantage over using the literal form.

With this, we can end this discussion about Objects in JavaScript and can start walking on the Path of defining and describing important topics related to objects.



My Personal Notes arrow_drop_up

FullStack Developer of six websites Verified Freelancer with 19 complete projects and 4.9 rating Modest Lifelong Learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.