Here Is All You Need To Know About JavaScript Objects

Posted by TotalDC

JavaScript objects are its most important data type and form the building blocks of modern JavaScript. These objects are quite different from JavaScript’s primitive data types (number, string, boolean, null, undefined, and symbol) in the sense that these primitive data types all store a single value each (depending on their types).

Here is what you will find in this article:

here is all you need to know about javascript objects
  • Objects are more complex and each object may contain any combination of these primitive data types as well as reference data types.
  • An object is a reference data type. Variables that are assigned a reference value are given a reference or a pointer to that value. That reference or pointer points to the location in memory where the object is stored. The variables don’t store the value.
  • Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and are called properties and methods, respectively, in the context of an object.

An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where a key is a string and value can be anything. JavaScript object would look like this:

let person = {
    name : "John",
    location : "New York",
    age: "30"
}

In the example above “name“, “location“, “age” are all keys, and “John“, “New York” and 30 are values of these keys respectively.

Each of these keys is referred to as properties of the object. An object in JavaScript may also have a function as a member, in which case it will be known as a method of that object.

// javascript code demonstrating a simple object
let person = {
    name : "John",
    location : "New York",
    age: "30",
    displayInfo : function(){
        console.log(`${person.name} lives 
              in ${person.location} for ${person.age}`);
    }
}
person.displayInfo();   

In the above example, “displayinfo” is a method of the person object that is being used to work with the object’s data, stored in its properties.

JavaScript Object Properties

The property names can be strings or numbers. In case the property names are numbers, they must be accessed using the “bracketed notation” like this:

// javascript code demonstrating a simple object
let person = {
    name : "John",
    location : "New York",
    age: "30",

    20:1000,
    displayInfo : function(){
        console.log(`${person.name} lives 
              in ${person.location} for ${person.age}`);
    }
}
person.displayInfo(); 

In this case, the value of key 20 is 1000.

Property names can also be strings with more than one space-separated word. In this case, these property names must be enclosed in quotes.

let office = {
    "office name" : "Boring office",
}

Like property names which are numbers, they must be accessed using the brackets. Like if we want to access “Boring” from “Boring Office” we can do something like this:

let office = {
    name : "Boring office",
    displayInfo : function(){
    console.log(`${office.name.split(' ')[0]}`);
  }
}
person.displayInfo(); //Boring

JavaScript Inherited Properties

Inherited properties of an object are those properties that have been inherited from the object’s prototype, as opposed to being defined for the object itself, which is known as the object’s property. To verify if a property is an object’s Own property, we can use the hasOwnProperty method.

JavaScript Property Attributes

Data properties in JavaScript have four attributes.

  • value: The property’s value.
  • writable: When true, the property’s value can be changed
  • enumerable: When true, the property can be iterated over by “for-in” enumeration. Otherwise, the property is said to be non-enumerable.
  • configurable:If false, attempts to delete the property, change the property to be an access-or property, or change its attributes (other than [[Value]], or changing [[Writable]] to false) will fail.
// hasOwnProperty code in js
const object1 = new Object();
object1.property1 = 42;
  
console.log(object1.hasOwnProperty('property1')); // true

Creating JavaScript Objects

There are several ways to create objects. One of which, known as the Object literal syntax, we have already used. Besides the object literal syntax, objects in JavaScript may also be created using the constructors, Object Constructor, or the prototype pattern.

  • Using the Object literal syntax: Object literal syntax uses the {…} notation to initialize an object and its methods/properties directly. Let’s look at an example of creating objects using this method :
let obj = {
    member1 : value1,
    member2 : value2,
};

These members can be anything – strings, numbers, functions, arrays, or even other objects. An object like this is referred to as an object literal. This is different from other methods of object creation which involve using constructors and classes or prototypes, which have been discussed below.

  • Object Constructor: Another way to create objects in JavaScript involves using the Object constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows you to initialize new objects. Example :
const person= new Object();
person.name = 'Paul';
person.location = 'New York';
person.date= 1990;
  
person.displayInfo = function(){
    console.log(`${person.name} was born
          in ${person.established} in  ${person.location}`);
}
  
person.displayInfo();

The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduce this burden significantly.

  • Constructors in JavaScript, like in most other OOP languages, provide a template for the creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor.
function Vehicle(name, maker) {
   this.name = name;
   this.maker = maker;
}
  
let car1 = new Vehicle('Mustang', 'Ford');
let car2 = new Vehicle('Santa Fe', 'Hyundai')
  
console.log(car1.name);    // Output: Mustang
console.log(car2.name);    // Output: Santa Fe

Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword in this manner before any function turns it into a constructor. What the “new Vehicle()” actually does is :

  • It creates a new object and sets the constructor property of the object to schools (It is important to note that this property is a special default property that is not enumerable and cannot be changed by setting a “constructor: someFunction” property manually).
  • Then, it sets up the object to work with the Vehicle function’s prototype object ( Each function in JavaScript gets a prototype object, which is initially just an empty object but can be modified. The object, when instantiated inherits all properties from its constructor’s prototype object).
  • Then calls Vehicle() in the context of the new object, which means that when the “this” keyword is encountered in the constructor(vehicle()), it refers to the new object that was created in the first step.
  • Once this is finished, the newly created object is returned to car1 and car2(in the above example).

Inside classes, there can be special methods named constructor().

class people {
    constructor()
    {
        this.name = "Paul";
    }
}
  
let person1 = new people();
  
// Output : Paul
console.log(person1.name);

Having more than one function in a class with the name of constructor() results in an error.

  • Another way to create objects involves using prototypes. Every JavaScript function has a prototype object property by default(it is empty by default). Methods or properties may be attached to this property. A detailed description of prototypes is beyond the scope of this introduction to objects.
let obj = Object.create(prototype_object, propertiesObject)
          // the second propertiesObject argument is optional

An example of making use of the Object.create() method is:

let players= {
    position: "Striker"
}
   
let player1 = Object.create(players);
   
    // Output : Striker    
console.log(player1.position);

In the example above players served as prototypes for creating the object “player1”.

All objects created in this way inherit all properties and methods from their prototype objects. Prototypes can have prototypes and those can have prototypes and so on. This is referred to as prototype chaining in JavaScript. This chain terminates with the Object.prototype which is the default prototype fallback for all objects. Javascript objects, by default, inherit properties and methods from Object.prototype but these may easily be overridden. It is also interesting to note that the default prototype is not always Object.prototype.For example, Strings and Arrays have their own default prototypes – String.prototype and Array.prototype respectively.

Accessing JavaScript Object Members

Object members(properties or methods) can be accessed using the :

  • dot notation:
(objectName.memberName)
let person= {
    name : "Paul",
    location : "New York",
    born: 1990,
    20 : 1000,
    displayinfo : function() {
        console.log(`${person.name} was born 
          in ${person.born} at ${person.location}`);
    }
  
}
  
console.log(person.name);
  
console.log(person.established);
  • Bracket Notation:
objectName["memberName"]
let person= {
    name : "Paul",
    location : "New York",
    born: 1990,
    20 : 1000,
    displayinfo : function() {
        document.write(`${person.name} was born
          in ${person.born} in ${person.location}`);
    }
}
  
// Output : Paul
console.log(person['name']); 
  
// Output: 1000
console.log(person['20']); 

Unlike the dot notation, the bracket keyword works with any string combination, including, but not limited to multi-word strings.

somePerson.first name // invalid
    somePerson["first name"] // valid

Unlike the dot notation, the bracket notation can also contain names which are results of any expressions variables whose values are computed at run-time.

let key = "first name" somePerson[key] = "Name Surname"

Similar operations are not possible while using the dot notation.

Iterating Over All Keys Of JavaScript Object

To iterate over all existing enumerable keys of an object, we may use the for… in construct. It is worth noting that this allows you to access only those properties of an object which are enumerable. For instance, properties inherited from the Object.property are not enumerable. But, enumerable properties inherited from somewhere can also be accessed using for… in construct.

let person = {
    gender : "male"
}
  
var person1 = Object.create(person);
person1.name = "Paul";
person1.age = 30;
person1.nationality = "American";
  
for (let key in person1) {
// Output : name, age, nationality 
// and gender
    console.log(key); 
}   

Deleting JavaScript Object Properties

To delete a property of an object we can make use of the delete operator. An example of its usage has been listed below:

let obj1 = {
    propfirst : "Name"
} 
  
// Output : Name
console.log(obj1.propfirst); 
delete obj1.propfirst
  
// Output : undefined
console.log(obj1.propfirst);

It is important to note that we can not delete inherited properties or non-configurable properties in this manner.

let obj1 = {
    propfirst : "Name"
} 
// Output : Name
console.log(obj1.propfirst) 
  let obj2 = Object.create(obj1);
  
 // Output : Name
  console.log(obj2.propfirst);
    
  // Output : true.
  console.log(delete obj2.propfirst); 
  
    // Surprisingly Note that this will return true
    // regardless of whether the deletion was successful
  
    // Output : Name    
    console.log(obj2.propfirst);