top of page

What are Objects in JavaScript? How to Create JavaScript Object?

Updated: Jun 7, 2023


JavaScript Object

JavaScript Object is the most important data type and serves as the building block for modern JavaScript. Unlike primitive data types in JavaScript (such as numbers, strings, booleans, null, undefined, and symbols) that store a single value, objects are more complex. An object can contain a combination of primitive data types and reference data types.


In JavaScript, an object is a reference data type. When a variable is assigned a reference value, it is given a reference or pointer to that value. This reference or pointer points to the memory location where the object is stored, and the variables do not actually store the value themselves.


Simply put, objects in JavaScript can be defined as an unordered collection of related data, consisting of primitive or reference types, represented as "key: value" pairs. The keys can be variables or functions, referred to as properties and methods, respectively, within the context of an object.


In JavaScript, an object represents an entity with its own state and behavior, expressed through properties and methods. For example, a car, pen, bike, chair, glass, keyboard, or monitor can be considered objects.


JavaScript is an object-based language, meaning that everything in JavaScript is an object.

You can create an object using curly braces { } with an optional list of properties. A property is a "key: value" pair, where the key is a string (also known as a "property name") and the value can be anything.

To better understand this abstract definition, let's take an example of a JavaScript object:

let school = {
    name: "Delhi Public School",
    location: "Delhi",
    established: "1971"
};

In the above example, "name," "location," and "established" are all keys, while "Delhi Public School," "Delhi," and 1971 are the respective values of these keys.


Each of these keys is referred to as a property of the object. An object in JavaScript can also have a function as a member, in which case it is called a method of that object.


Creating JavaScript Object

There are 3 ways to create objects.

  1. By object literal

  2. By creating an instance of Object directly (using a new keyword)

  3. By using an object constructor (using a new keyword)


1. By Object Literal

It is the simplest way. With Object Literal, you can define and create an object in a single statement. It involves using a list of name:value pairs (such as age:50) enclosed in curly braces {} called an object literal.


Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = {firstName:"John", lastName:"Doe", age:50,eyeColor:"blue"};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Output:

JavaScript Object - By Object Literal






2. Using the JavaScript Keyword new

Another way to create a JavaScript object is by using the keyword "new". In this method, you can use the "new Object()" syntax to create a new object, and then add properties to it.


The following example creates a new JavaScript object using new Object(), and then adds 4 properties:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue"; 

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Output:

JavaScript Object - By JavaScript Keyword new






3. By using an object constructor (using a new keyword)

In this method, you define a constructor function that serves as a blueprint for creating objects with similar properties and behaviors.


When you create an object using the constructor function and the "new" keyword, you are actually creating a reference to that object, not a separate copy. This means that if you assign this object to another variable, both variables will refer to the same object in memory.


For example:

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

const person = new Person("John", 25);
const x = person; // Both x and person refer to the same object.

x.age = 30;
console.log(person.age); // Output: 30

In the code above, we define a constructor function called "Person" that takes in a name and age parameter. We then create a new object called "person" using the constructor function and assign it to the variable "x". Both "x" and "person" refer to the same object in memory.


If we modify a property of "x", such as changing the age to 30, the corresponding property in the "person" object will also be affected. This is because "x" and "person" are simply references to the same object, so any changes made to one will be reflected in the other.


Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>JavaScript objects are mutable.</p>
<p>Any changes to a copy of an object will also change the original object:</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age:50,
  eyeColor: "blue"
};

const x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Output:

JavaScript Object








Accessing Object Properties

Accessing object properties in JavaScript can be done using two notations:

  1. Dot notation

  2. Bracket notation.

1. Dot Notation: Using dot notation, you can access the value of a property by specifying the object name followed by a dot and then the property name. The syntax is as follows:

objectName.propertyName

For example:

const person = {
    name: 'John',
    age: 20,
};

// Accessing property using dot notation
console.log(person.name); // Output: John

In the above code, we have an object called "person" with properties "name" and "age". By using dot notation, we access the value of the "name" property as person.name, which will output "John".


2. Bracket Notation: Using bracket notation, you can access the value of a property by specifying the object name followed by square brackets containing the property name as a string. The syntax is as follows:

objectName["propertyName"]

For example:

const person = {
    name: 'John',
    age: 20,
};

// Accessing property using bracket notation
console.log(person["name"]); // Output: John

In the above code, we again have the "person" object. By using bracket notation, we access the value of the "name" property as a person["name"], which will also output "John".


Both Dot notation and Bracket notation achieve the same result of accessing object properties. Dot notation is commonly used when the property name is a valid identifier (no spaces or special characters), while bracket notation is useful when the property name is dynamic, stored in a variable, or contains spaces or special characters.



JavaScript Object Methods

In JavaScript, an object can also include functions as properties. For example:

const person = {
    name: 'Sam',
    age: 30,
    greet: function() {
        console.log('hello');
    }
};

person.greet(); // Output: hello

In the above code, the person object has a property called greet, which is assigned a function as its value. To call the function inside the object, we use person.greet().


In JavaScript, a method is a property that contains a function declaration. It allows objects to have behaviors associated with them.


Here are various methods of the Object built-in object in JavaScript:

  • Object.assign(): Copies enumerable and own properties from a source object to a target object.

  • Object.create(): Creates a new object with the specified prototype object and properties.

  • Object.defineProperty(): Describes behavioral attributes of a property.

  • Object.defineProperties(): Creates or configures multiple object properties.

  • Object.entries(): Returns an array with arrays of key-value pairs.

  • Object.freeze(): Prevents existing properties from being removed.

  • Object.getOwnPropertyDescriptor(): Returns a property descriptor for a specified property of an object.

  • Object.getOwnPropertyDescriptors(): Returns all own property descriptors of a given object.

  • Object.getOwnPropertyNames(): Returns an array of all properties (enumerable or not) found.

  • Object.getOwnPropertySymbols(): Returns an array of all own symbol key properties.

  • Object.getPrototypeOf(): Returns the prototype of a specified object.

  • Object.is(): Determines whether two values are the same value.

  • Object.isExtensible(): Determines if an object is extensible.

  • Object.isFrozen(): Determines if an object is frozen.

  • Object.isSealed(): Determines if an object is sealed.

  • Object.keys(): Returns an array of the given object's own property names.

  • Object.preventExtensions(): Prevents any extensions of an object.

  • Object.seal(): Prevents new properties from being added and marks existing properties as non-configurable.

  • Object.setPrototypeOf(): Sets the prototype of a specified object to another object.

  • Object.values(): Returns an array of values.

These methods provide various functionalities for working with objects in JavaScript.


Deleting a Property of an Object

To delete a property from an object in JavaScript, you can use the delete operator followed by the object name and the property name you want to remove. The syntax is as follows:

delete objectName.propertyName;

For example, let's say we have an object called a person with properties such as name, age, and city. If we want to remove the age property from the person object, we can do it like this:

delete person.age;

After executing the delete statement, the age property will be removed from the person object.


It's important to note that if you attempt to access the deleted property after deletion, you will get an undefined value. For example:

console.log(person.age); // Output: undefined

In the above code, trying to access the age property of the person object after deleting it will return undefined.


Deleting a property allows you to remove unnecessary or unwanted properties from an object, thereby managing the object's structure and contents.


Checking if a Property Exists

To check if a property exists in an object in JavaScript, you can use the in operator followed by the property name and the object name. The syntax is as follows:

propertyName in objectName;

For example, let's say we have an object called employee with properties like firstName, lastName, and employeeId. If we want to check if the ssn and employeeId properties exist in the employee object, we can do it like this:

let employee = {
    firstName: 'Peter',
    lastName: 'Doe',
    employeeId: 1
};

console.log('ssn' in employee);
console.log('employeeId' in employee);

Output:

false
true

After executing the in operator, it will return true if the property exists in the object and false if it doesn't.

In the above example, since the ssn property doesn't exist in the employee object, the first console.log('ssn' in employee); will output false. On the other hand, the employeeId property does exist, so the second console.log('employeeId' in employee); will output true.


Using the in operator allows you to check if a specific property exists in an object before accessing its value. This can be useful for conditional checks or to avoid potential errors when working with object properties.


Conclusion

To summarize:

  1. An object in JavaScript is a collection of key-value pairs. It allows you to store and organize related data.

  2. You can access a property of an object using either the dot notation (.) or the array-like notation ([]). The dot notation is used when you know the property name beforehand, while the array-like notation is useful when the property name is stored in a variable or contains special characters.

  3. To remove a property from an object, you can use the "delete" operator followed by the object name and the property name. For example: delete objectName.propertyName;

  4. The "in" operator is used to check if a property exists in an object. It returns true if the property is present and false otherwise. The syntax is: propertyName in objectName;

These concepts are fundamental to working with objects in JavaScript. Objects provide a powerful way to structure and organize data, and understanding how to access, delete, and check for properties is essential for effective object manipulation.

0 comments
bottom of page