Introduction to Objects


An object aggregates multiple values and allows you to store and retrieve those values by name.

An object is an unordered collection of properties, each of which has a name and a value. Property names are usually strings so we can say that objects map strings to values.

In addition to maintaining its own set of properties, a JavaScript object also inherits the properties of another object, known as its “prototype.”

Any value in JavaScript that is not a string, a number, a Symbol, or true, false, null, or undefined is an object. And even though strings, numbers, and booleans are not objects, they can behave like immutable objects.

Objects are mutable and manipulated by reference rather than by value. If the variable x refers to an object and the code let y = x; is executed, the variable y holds a reference to the same object, not a copy of that object. Any modifications made to the object through the variable y are also visible through the variable x.


In this blog, we’ll deep dive into objects with examples to understand how objects work under the hood in javascript.


Creating Objects


There are 3 ways to create an object in javascript. The following ways are discussed below:


1. Object literals

An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces.


let emptyVar = {};                //An object with no properties

let pointVar = { x: 0, y: 0 };   //Two numeric properties


2. Creating Objects with new

The new operator creates and initializes a new object. The new keyword must be followed by a function invocation. A function used in this way is called a constructor and serves to initialize a newly created object.


let o_var = new Object();      // Create an empty object: same as {}

let a_var = new Array();       // Create an empty array: same as []

let m_var = new Map();         // Create a Map object for key/value mapping


3. Object.create()

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.


const orgObject = { company: 'ABC' };

const employee = Object.create(orgObject, { name: { value: 'EmployeeOne' } });

console.log(employee);          // { company: "ABC" }

console.log(employee.name);     // "EmployeeOne"



The Object.create method, takes two parameters. The first parameter is a mandatory object that serves as the prototype of the new object to be created. The second parameter is an optional object which contains the properties to be added to the new object.


Querying and Setting Properties


To obtain the value of a property, use the dot (.) or square bracket ([]) operators.


let author = book.author;       // Get the "author" property of the book.

let title = book["main title"]; // Get the "main title" property of the book.


To create or set a property, use a dot or square brackets as you would to query the property, but put them on the left-hand side of an assignment expression:


book.edition = 7;                   // Create an "edition" property of book.

book["main title"] = "ECMAScript"; // Change the "main title" property.


Deleting Object Properties 


The delete operator removes a property from an object. If the property’s value is an object and there are no more references to the object, the object held by that property is eventually released automatically.


delete book.author;         // The book object now has no author property.

delete book["main title"]; // Now it doesn't have "main title", either.


A delete expression evaluates to true if the delete succeeded or if the delete had no effect (such as deleting a nonexistent property). delete also evaluates to true when used (meaninglessly) with an expression that is not a property access expression.


Object properties



hasOwnProperty()


The hasOwnProperty() method of an object tests whether that object has its own property with the given name. It returns false for inherited properties:


let o = { x: 1 };
o.hasOwnProperty("x")      // => true: o has an own property x
o.hasOwnProperty("y")     // => false: o doesn't have a property y


in operator


The in operator expects a property name on its left side and an object on its right. It returns true if the object has its own property or an inherited property by that name:


let obj = { x: 1 };
"x" in obj // => true: obj has an own property "x"
"y" in obj // => false: obj doesn't have a property "y"


Extending Objects


A common operation in JavaScript programs is needing to copy the properties of one object to another object. In ES6, this ability comes to the core JavaScript language in the form of Object.assign(). Object.assign() expects two or more objects as its arguments. It modifies and returns the first argument, which is the target object but does not alter the second or any subsequent arguments, which are the source objects.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target); //output: Object { a: 1, b: 4, c: 5 }


Serializing Objects


Object serialization is the process of converting an object’s state to a string from which it can later be restored. The functions JSON.stringify() and JSON.parse() serialize and restore JavaScript objects.


let o = {x: 1, y: {z: [false, null, ""]}}; // Define a test object
let s = JSON.stringify(o); // s == '{"x":1,"y":{"z": [false,null,""]}}'
let p = JSON.parse(s); // p == {x: 1, y: {z: [false, null, ""]}}


Extended Object Literal Syntax


Recent versions of JavaScript have extended the syntax for object literals in a number of useful ways. The following section explains these extensions.

1. Shorthand Properties



Prior to ES6, an object literal is a collection of name-value pairs. With basic object literal syntax, you’d end up repeating each identifier twice:


function createMachine(name, status) {
  return {
  name: name,
  status: status
  };
}


In ES6 and later, you can drop the colon and one copy of the identifier and end up with much simpler code:


function createMachine(name, status) {
  return {
  name,
  status
  };
}


2. Computed property name


Prior to ES6, you could use the square brackets( []) to enable the computed property names for the properties on objects.


The square brackets allow you to use the string literals and variables as the property names.


let name = 'machine name';
let machine = {
  [name]: 'server',
  'machine hours': 10000
};
console.log(machine[name]); // server
console.log(machine['machine hours']); // 10000


The name variable was initialized to a value of ‘machine name’. Since both properties of the machine object contain a space, you can only reference them using the square brackets.

In ES6, the computed property name is a part of the object literal syntax, and it uses the square bracket notation.


let prefix = 'machine';
let machine = {
  [prefix + ' name']: 'server',
  [prefix + ' hours']: 10000
};
console.log(machine['machine name']); // server
console.log(machine['machine hours']); // 10000



The machine object’s properties evaluate as ‘machine name’ and ‘machine hours’, therefore you can reference them as the properties of the machine object.


3. Concise method syntax


Prior to ES6, when defining a method for an object literal, you need to specify the name and full function definition as shown in the following example:


let server = {
  name: "Server",
  restart: function () {
    console.log("The" + this.name + " is restarting…");
  }
};

ES6 makes the syntax for making a method of the object literal more concise by removing the colon (:) and the function keyword.

let server = {
  name: 'Server',
  restart() {
    console.log("The" + this.name + " is restarting…");
  }
};


4. Spread Operator


ES6 provides a new operator called spread operator that consists of three dots (…). The spread operator allows you to spread out elements of an iterable object such as an array, map, or set. For example:

const odd = [1,3,5];
const combined = [2,4,6, …odd];
console.log(combined); //[ 2, 4, 6, 1, 3, 5 ]


Conclusion

This is the blogs which explains everything about objects from properties to assignments. I hop you understood about objects.

If you have any doubts, let us know in comments.