Skip to main content

Front-End Development

The Power Of Objects In JavaScript: Part 2

Learning from collaboration

Jump into the fascinating world of JavaScript objects with us! We’re going to explore cool methods and tricks that can make your coding skills even better. If you’re new to objects in JavaScript, no stress! Our guide, ” The Power of Objects in Javascript: Part 1” is there to help. It breaks down both the basics and some advanced stuff, so check out the blog for a smooth journey into understanding how objects work in JavaScript. Go ahead and take a peek!

Object Built-in Methods

Built-in methods are functions that are already present in the JavaScript language and may be applied straight to objects. These methods are built into data types or objects and provide common functionality. Here’s a quick overview with thorough examples of various built-in methods for objects.

  • keys()

The method returns an array list that contains all the enumerable attributes of an object.

Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};
let keys = Object.keys(myObject1);
console.log(keys);

Output:

Picture1

  • values()

    The method returns an array list that contains all the enumerable properties of an object.

Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};
let values = Object.values(myObject1);
console.log(values);

Output:

Picture2

  • entries()

An array list of keys and values for an object’s properties is returned using this method.

Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};
let entries = Object.entries(myObject1);
console.log(entries);

Output:
Picture3

  • assign()

All the properties of one or more source objects are copied to the target object by this method.
Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};

const myObject2 = { 
 hobby: 'reading',
 power: 'lighting'
};
let mergedObjects = Object.assign({} ,myObject1,myObject2);
console.log(mergedObjects);

Output:
Picture4

  • hasOwnProperty()

This method checks if an object has a specific property as its own property, returning a Boolean.

Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};

console.log(myObject1.hasOwnProperty('firstName'));
console.log(myObject1.hasOwnProperty('hobby'));

Output:

Picture6

  • freeze()

Freezing an object prevents the addition of new properties, the removal of existing properties, and the modification of values through this method.
Example:

//JavaScript
const myObject1 = { 
  firstName: "Percy" ,
  lastName: "Jackson",
  age: 18,
};

// Attempt to add a new property
Object.freeze(myObject1);
myObject1.hobby = 'travelling' // Ignored in strict mode
console.log(myObject1);

Output:
Picture7

  • fromEntries()

This method generates an object from an array of key-value pairs.

Example:

//JavaScript
let entries = [['firstName', 'Harry'], ['lastName', 'Potter'], ['year', 2001]];
let Movie = Object.fromEntries(entries);

Output:
Picture8

Loops and Objects: A Dynamic Duo

  • entries() with forEach()

    Combining Object.entries() with forEach() can be powerful for iterating through key-value pairs.

    Example:

    //JavaScript
    const myObject1 = { 
      firstName: "Percy" ,
      lastName: "Jackson",
      year: 2024,
    };
    Object.entries(myObject1).forEach(([key, value]) => {
      console.log(`${key}: ${value}`);
    });

    Output:
    Picture9

  •  ..in loop

Example:

//JavaScript
const myObject2 = { 
  firstName: "Harry" ,
  lastName: "Potter",
  year: 2001,
};
for(const key in myObject2){
  console.log(`${key}: ${myObject2[key]}`);
}

Output:
Picture10

Accessors: Elevating Control with Getters and Setters

Accessors provide a way to control access to object properties, ensuring a more streamlined interaction with data.

Getter:

The value of a property is accessed using the getter method. It is represented by the get keyword.

Example:

//JavaScript
const person = {
  _name: 'Harry', // Using underscore convention to indicate a private property
  get name() {
    return this._name;
  }
};

console.log(person.name);

In this example, the get name() method allows you to access the value of the _name property without directly accessing it.
Output:
Picture11

Setter:

The value of a property can be modified using a setter method. It is defined using the set.

Example:

//JavaScript
const person = {
  _name: 'Harry',
  set name(newName) {
    this._name = newName;
  }
};

person.name = 'Nesta';
console.log(person._name);

The set name(newName) method allows you to set a new value for the _name property using the assignment person.name = ‘Nesta’.

Output:

Picture12

Accessors are useful for controlling the access and modification of object properties, providing a way to encapsulate logic, and ensuring proper handling of data.

How to Create a Copy of an Object and What Not to Do When Creating

In JavaScript, assigning an object to another variable creates a reference to the original object rather than a new copy. This means that any changes made to either the original or the new variable will affect both objects. To create object clones with identical attributes as the original, methods must be used. Let’s explore both scenarios:

Example:

//JavaScript
// Creating a reference to the original object
let originalObject = { key: 'value' };
let referenceObject = originalObject;

// Modifying the reference object
referenceObject.key = 'new value';

console.log(originalObject);

In this case, both originalObject and referenceObject point to the same object in memory, so modifying one reflects on the other.

Output:
Picture13

Creating a Copy:

  • Using Object.assign()

Example:

//JavaScript
// Creating a shallow copy using Object.assign()
let originalObject = { key: 'value' };
let copyObject = Object.assign({}, originalObject);

// Modifying the copy object
copyObject.key = 'new value';

console.log(originalObject);
console.log(copyObject);

Output:

Picture14

  • Using the Spread Operator (…)

Example:

Javascript
// Creating a shallow copy using the spread operator
let originalObject = { key: 'value' };
let copyObject = { ...originalObject };

// Modifying the copy object
copyObject.key = 'new value';

console.log(originalObject);
console.log(copyObject);

Output:

  Picture15         

The methods using Object.assign() and the spread operator () create new objects, ensuring that modifications to the copy do not affect the original object. Keep in mind that these methods create shallow copies, meaning nested objects will still be references. To create deep copies of nested objects, one may need to take into account additional considerations.

Conclusion

Objects in JavaScript provide a powerful mechanism for structuring and organizing data. By leveraging its methods, developers can efficiently work with objects and build more maintainable and robust code. As you delve deeper into JavaScript development, mastering objects, and their methods will undoubtedly enhance your ability to create dynamic and scalable web applications. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Aafreen Akhtari

Aafreen Akhtari is an Associate Technical Consultant at Perficient in Nagpur with over 2 years of experience in the IT industry. Her expertise lies in UI development, where she works with various front-end technologies. Aafreen is passionate about reading and singing in her free time.

More from this Author

Follow Us