Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Javascript Objects

Last Updated on July 28, 2023 by Mayank Dham

In JavaScript, objects play a fundamental role as they enable us to represent and work with complex data structures. An object is a collection of key-value pairs, where each key represents a property and the corresponding value can be any data type, including primitive types (such as numbers, strings, and booleans) or even other objects. Objects are the building blocks for creating reusable and organized code in JavaScript.

How to create JavaScript Objects?

There are various ways to create objects in JavaScript. We will be learning about all of the JavaScript create object methods in detail

1. Object Initializers (Object Literals)

Object initializers, also known as object literals, are a concise way to create objects. To define an object using an object initializer, we use curly braces and define properties with their respective values.

const person = {
  name: "John Doe",
  age: 30,
  gender: "male",
};

2. Constructor Functions and the "new" Operator

Constructor functions are used to create multiple instances of objects with similar properties and behaviors. The function acts as a blueprint for the object, and the "new" operator is used to create instances.

function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}

const person1 = new Person("John Doe", 30, "male");
const person2 = new Person("Jane Smith", 25, "female");

3. Using the Object.create() Method

The Object.create() method allows us to create new objects with a specified prototype object. This method is useful when we want to create an object based on an existing prototype without using constructor functions.

const animal = {
  type: "Invertebrates",
  displayType() {
    console.log(this.type);
  },
};

const animal1 = Object.create(animal);
animal1.displayType(); // Logs: Invertebrates

const fish = Object.create(animal);
fish.type = "Fishes";
fish.displayType(); // Logs: Fishes

Working with JavaScript Object Properties

So far we’ve learned how we can create javascript objects. Now let us see how we can work with js objects.

  1. Accessing Properties

The properties of an object can be accessed using either dot notation or bracket notation.

const person = {
  name: "John Doe",
  age: 30,
};
console.log(person.name); 
console.log(person["age"]); 

Output

John Doe
30

2. Adding and Deleting Properties

Properties can be added or deleted from an object dynamically using assignment and the "delete" keyword.

const car = {
  make: "Toyota",
  model: "Camry",
};

car.year = 2022; // Adding a new property
console.log(car); 

delete car.model; // Deleting a property
console.log(car); 

Output

make: "Toyota", model: "Camry", year: 2022
make: "Toyota", year: 2022

3. Defining Methods in Objects

In JavaScript, methods are functions that are associated with an object. They can be defined directly within an object or added later using object assignment.

const person = {
  name: "John Doe",
  age: 30,
  sayHello: function () {
    console.log(Hello, my name is ${this.name}.);
  },
};

person.sayHello(); 

Output

Hello, my name is John Doe

4. Getters and Setters in JavaScript

Getters and setters are special methods that allow controlled access to an object’s properties. Getters retrieve the value of a property, while setters modify the value.

const rectangle = {
  width: 0,
  height: 0,
  get area() {
    return this.width * this.height;
  },
  set dimensions({ width, height }) {
    this.width = width;
    this.height = height;
  },
};

rectangle.dimensions = { width: 5, height: 10 };
console.log(rectangle.area); 

Output

50

5. Comparing JavaScript Objects

In JavaScript, objects are reference types, and two distinct objects with the same properties are not considered equal, even if their properties have the same values.

const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };

console.log(obj1 == obj2); 
console.log(obj1 === obj2);

Output

False
False 

Javascript Object Methods
The various Javascript object methods are shown below in tabular form.

S.No Methods Description
1 Object.assign() This technique is utilized for copying own and enumerable properties from a source object to a target object
2 Object.create() This method is used to create a new object with the prototype object and properties specified.
3 Object.defineProperty() This method is used to describe some of the property’s behavioral characteristics.
4 Object.defineProperties() Multiple object properties can be created or configured using this method.
5 Object.entries() This method returns an array containing arrays of key-value pairs.
6 Object.freeze() This method prevents the removal of existing properties.
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified object’s property.
8 Object.getOwnPropertyDescriptors() This method returns all of an object’s own property descriptors.
9 Object.getOwnPropertyNames() The returned array includes every property (enumerable or not) found.
10 Object.getOwnPropertySymbols() This method returns an array containing all of your own symbol key properties.
11 Object.getPrototypeOf() The prototype of the specified object is returned by this method.
12 Object.is() This approach determines if there is a single value.
13 Object.isExtensible() This method determines whether or not an object is extensible.
14 Object.isFrozen() This method determines whether or not an object was frozen.
15 Object.isSealed() This method determines whether or not an object is sealed.
16 Object.keys() This method returns an array of the names of the properties of the given object.
17 Object.preventExtensions() This method is used to prevent an object from extending.
18 Object.seal() This method prevents the addition of new properties and marks all existing properties as non-configurable.
19 Object.setPrototypeOf() This method assigns the prototype of one object to another.
20 Object.values() This method returns a value array.

Conclusion
Understanding JavaScript objects and creating custom objects is essential for effective programming in JavaScript. Objects allow us to structure data in a meaningful way, and custom objects enable us to model complex entities with specific properties and behaviors. By leveraging these concepts, JavaScript developers can build scalable and maintainable applications.

Frequently Asked Questions (FAQs)

Here are some of the most frequently asked questions about Javascript Objects

Q1: What is a method in JavaScript?
A method in JavaScript is a function associated with an object. It allows objects to perform specific actions or behaviors. Methods are defined within an object and are used to manipulate data, interact with other objects, or perform computations. To call a method, you use the object name followed by the method name, along with parentheses.

Q2: What is an object in JavaScript?
An object in JavaScript is a data structure that represents a real-world entity or concept. It encapsulates data, known as properties or attributes, and the methods (actions or behaviors) that can be performed on the data. JavaScript objects are fundamental to object-oriented programming (OOP), where they are instances of classes or blueprints that define their structure and behavior.

Q3: What are methods in JavaScript used for?
Methods in JavaScript are used to define the behavior of objects. They enable objects to perform actions, computations, or interactions with other objects or external resources. Methods allow us to organize code by associating specific functionalities with the relevant objects, promoting modularity and reusability.

Q4: What is the difference between object properties and methods?
The main difference between object properties and methods lies in their purpose and the data they hold:

Object Properties: Properties are data members of an object, representing its characteristics or attributes. They store values, which can be any data type, such as strings, numbers, booleans, arrays, or even other objects.

Methods: Methods are functions associated with an object, defining its actions or behaviors. They perform computations, modify properties, or interact with other objects. Methods are used to enable objects to perform specific tasks.

Q5: How are methods used in Object-Oriented Programming (OOP)?
In Object-Oriented Programming, a method is a function defined within a class or object. It represents a behavior that the class or object can exhibit. Methods allow objects to interact with their internal data and provide a way to perform specific actions related to the object’s behavior. In OOP, objects are created from classes, and these objects can use the methods defined in the class to perform various tasks.

Leave a Reply

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