JavaScript Objects

In this tutorial, you will learn about JavaScript objects and how to use them in your code. You will learn about object properties, methods, and how to access and manipulate them. You will also learn about prototypes, the 'this' keyword, constructors, getters and setters, object iteration, and more.

Why should you use it?

  • Objects are used to store data in a structured way.
  • Objects can be used to create reusable code.
  • Objects can be used to create complex data structures.

What are Objects?

Objects are a fundamental data structure in JavaScript. They are collections of key-value pairs, which are used to store and access data. Objects are similar to arrays, but instead of using indexes to access data, they use keys. Keys can be strings, numbers, or symbols. Values can be any data type, including objects. Objects are declared using curly braces, and the key-value pairs are separated by commas. Keys are always followed by a colon, and values can be followed by a comma. Here is an example of an object:
index.js
const person = {
  name: 'John',
  age: 30,
  gender: 'male'
};
To access the values stored in an object, we use dot notation. We can also use bracket notation, which is similar to array notation. Here is an example of accessing the values stored in an object:
index.js
const name = person.name; // John
const age = person['age']; // 30
To add a new key-value pair to an object, we use dot notation. Here is an example of adding a new key-value pair to an object:
index.js
person.country = 'United States';
To delete a key-value pair from an object, we use the delete keyword. Here is an example of deleting a key-value pair from an object:
index.js
delete person.age;

Object Properties

In JavaScript, objects can contain properties that can be accessed and modified. The properties of an object are defined as a name-value pair. The name is a string that is used to access the value. The value can be of any type, including functions, arrays, and other objects. Properties are typically added to an object when it is created, but they can also be added or removed at any time. To access a property of an object, use the dot notation: objectName.propertyName To set a property of an object, use the assignment operator: objectName.propertyName = value To delete a property of an object, use the delete keyword: delete objectName.propertyName Here is an example of an object with two properties:
index.js
const person = {
  name: 'John',
  age: 30
};

console.log(person.name); // 'John'
console.log(person.age); // 30

person.name = 'Jane';
person.age = 25;

console.log(person.name); // 'Jane'
console.log(person.age); // 25

delete person.age;

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

Object Methods

Object methods are functions that can be used on objects. They are used to add functionality to objects, and are used in a similar way to functions. They can be used to access and manipulate the properties of an object, and to create new objects.

Object methods are defined using the method() syntax. They can be used on any object, and can be called using the object.method() syntax. Let's look at an example of an object method.

index.js
const person = {
  name: 'John',
  age: 25,
  sayName() {
    console.log(this.name);
  }
};

person.sayName();

In the example above, we have an object with a sayName() method. This method logs the name property of the object to the console when it is called. We can call the sayName() method using the person.sayName() syntax. This will log the name property to the console.

Object methods can also be used to create new objects. In the example below, we have a createPerson() method that takes two parameters, name and age, and creates a new object with those properties. This new object is then returned from the method.

index.js
const createPerson = (name, age) => {
  const person = {
    name,
    age
  };
  return person;
};

const john = createPerson('John', 25);

console.log(john);

In the example above, we have a createPerson() method that takes two parameters, name and age. This method creates a new object with those properties, and returns the new object. We can call this method using the createPerson('John', 25) syntax, which will create a new object with the name and age properties set to John and 25 respectively.

Object methods are a powerful tool for manipulating and creating objects. They can be used to access and manipulate the properties of an object, and to create new objects. They are an essential part of working with objects in JavaScript.

To learn more about object methods, visit Object Methods.

Object Definition

Objects are collections of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.
index.js
const myObject = {
  name: 'John',
  age: 30
};

console.log(myObject);

Creating an Object

Objects can be created in JavaScript with the {} syntax.
index.js
const myObject = {};

console.log(myObject);

Accessing Properties

Properties can be accessed using dot notation or bracket notation.
index.js
const myObject = {
  name: 'John',
  age: 30
};

console.log(myObject.name); // John
console.log(myObject['age']); // 30

Adding Properties

Properties can be added to an object by using dot notation or bracket notation.
index.js
const myObject = {
  name: 'John',
  age: 30
};

myObject.location = 'New York';
myObject['country'] = 'USA';

console.log(myObject);

Deleting Properties

Properties can be deleted from an object using the delete operator.
index.js
const myObject = {
  name: 'John',
  age: 30
};

delete myObject.age;

console.log(myObject);

Object Methods

Objects can also have methods, which are functions associated with an object.
index.js
const myObject = {
  name: 'John',
  age: 30,
  sayName: function() {
    console.log(this.name);
  }
};

myObject.sayName(); // John

Object Access

JavaScript objects are collections of key-value pairs. The key is usually a string, while the value can be any type of data, including another object. Accessing and manipulating object values is an important part of working with JavaScript.

Objects can be accessed in two ways: dot notation and bracket notation. Dot notation is the most common way of accessing object values, and it uses a period to separate the object name and the property name. Bracket notation is less common, but it can be used when the object name or property name contains spaces or other special characters.

To access a value from an object, use the following syntax:

index.js
const person = {
  name: 'John'
};

const name = person.name;

console.log(name); // 'John'

In the example above, the object person has a property name with a value of "John". To access the value, we use dot notation and specify the object name followed by a period and the property name.

To access a value from an object using bracket notation, use the following syntax:

index.js
const person = {
  name: 'John'
};

const name = person['name'];

console.log(name); // 'John'

In the example above, the object person has a property name with a value of "John". To access the value, we use bracket notation and specify the object name followed by a pair of brackets containing the property name.

Objects can also be accessed using a combination of dot notation and bracket notation. This can be useful when the object name or property name contains spaces or other special characters.

index.js
const person = {
  'full name': 'John Smith'
};

const name = person.full name;

console.log(name); // 'John Smith'

In the example above, the object person has a property "full name" with a value of "John Smith". To access the value, we use a combination of dot notation and bracket notation. First, we use dot notation to access the object person, then we use bracket notation to access the property "full name".

Prototype

Prototype is an important concept in JavaScript. It is used to create objects and set their properties and methods. Every object in JavaScript has a prototype. It is an object that acts as the default parent of all objects. It is used to define properties and methods for all objects.

Prototype is used to add methods and properties to an object. It is a special type of object that contains methods and properties that are inherited by all objects. It is like a template for creating objects. You can create an object using the prototype object and then add methods and properties to it.

The prototype object can be used to add methods and properties to an object. It is a special type of object that contains methods and properties that are inherited by all objects. It is like a template for creating objects. You can create an object using the prototype object and then add methods and properties to it.

To create an object from a prototype, you use the Object.create() method. This method takes an object as an argument and returns a new object with the prototype of the argument object. The new object inherits all the properties and methods of the prototype object.

To add a method or property to an object, you can use the Object.defineProperty() method. This method takes two arguments: the object to which the property or method should be added and an object containing the property or method definition. The method returns the object with the new property or method.

To learn more about prototype, visit Prototype.

index.js
// Create a prototype object
let prototype = {
  sayHello: function () {
    console.log("Hello!");
  }
};

// Create an object using the prototype
let obj = Object.create(prototype);

// Call the sayHello method
obj.sayHello();

This

The this keyword in JavaScript is a reference to the object it belongs to. It is commonly used when defining object methods, to refer to the object of which the method is a property.

In JavaScript, the value of this is determined by how a function is called. In most cases, it refers to the object that owns the executing code. It can be assigned a different value when calling a function.

In the global execution context (outside of any function), this refers to the global object, whether in the browser or in Node.js.

Example

index.js
const person = {
  name: 'John Doe',
  age: 30,
  greet() {
    console.log('Hello, my name is ' + this.name);
  }
};

person.greet();

In the example above, this refers to the object person. In the method greet, we can use this to refer to the person object, and access its properties.

To learn more about this, visit This.

Constructor

A constructor is a special method used to create and initialize an object created within a class. The constructor is called when an object of a class is created. It can be used to set the properties of the object or to initialize the object itself.

In JavaScript, a constructor is a function used to create an object. The constructor is called with the new keyword, and it can accept parameters. The constructor is used to set the properties of the object, and to initialize the object itself.

The following example shows how to define a constructor in JavaScript:

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

The constructor can be used to set the properties of the object. The following example shows how to set the properties of an object using the constructor:

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

let person1 = new Person('John', 30);
let person2 = new Person('Mary', 25);

The constructor can also be used to initialize the object itself. The following example shows how to initialize the object using the constructor:

index.js
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    console.log('Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.');
  }
}

let person1 = new Person('John', 30);
person1.sayHello();

The constructor can be used to create objects with different properties. The following example shows how to create objects with different properties using the constructor:

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

let person1 = new Person('John', 30);
let person2 = new Person('Mary', 25);

console.log(person1);
console.log(person2);

To learn more about constructor, visit Constructor.

Getter and Setter

Getters and setters allow you to define custom behavior for getting and setting properties on objects. Getters and setters are used to create accessor properties, which provide a way to control how a property is accessed or set. Getters and setters provide a way to create read-only or write-only properties.

To create a getter, use the get keyword followed by a function. This function will be called when the property is accessed.

index.js
const person = {
  firstName: 'John',
  lastName: 'Doe',
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(person.fullName); // John Doe
      

To create a setter, use the set keyword followed by a function. This function will be called when the property is set.

index.js
const person = {
  firstName: 'John',
  lastName: 'Doe',
  set fullName(name) {
    const [firstName, lastName] = name.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
  }
};

person.fullName = 'Jane Doe';
console.log(person.firstName); // Jane
console.log(person.lastName); // Doe
      

Getters and setters can also be used to define read-only and write-only properties. To define a read-only property, omit the setter and define only a getter. To define a write-only property, omit the getter and define only a setter.

index.js
const person = {
  firstName: 'John',
  lastName: 'Doe',
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  set fullName(name) {
    const [firstName, lastName] = name.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;
  }
};

person.fullName = 'Jane Doe';
console.log(person.fullName); // Jane Doe
      

To learn more about getter and setter, visit Getter and Setter.

Object Iteration

Iterating over objects is a common task in JavaScript. It can be done in several ways. One of the most popular ways is to use the for...in loop. This loop will iterate over all of the properties of an object and return the key-value pairs.
index.js
const person = {
  name: 'John',
  age: 25
};

for (let key in person) {
  console.log(key, person[key]);
}
const person = { name: 'John', age: 25 }; for (let key in person) { console.log(key, person[key]); } The output of the code above would be: name John age 25 Another popular way of iterating over objects is to use the Object.keys() method. This method takes in an object and returns an array of keys that can be used to access the values of the object.
index.js
const person = {
  name: 'John',
  age: 25
};

const keys = Object.keys(person);
console.log(keys);
const person = { name: 'John', age: 25 }; const keys = Object.keys(person); console.log(keys); The output of the code above would be: [name, age]

Object Keys

In JavaScript, objects are collections of key/value pairs. Each key is a string, and each value can be any data type. The key is used to access the value associated with it. In order to access a value in an object, you need to know its key. This can be done using the object's key or using the bracket notation. To find out what keys an object has, you can use the Object.keys() method. This method takes an object as an argument and returns an array containing the object's keys.
index.js
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

console.log(Object.keys(person));
// Output: ['name', 'age', 'city']
In the example above, we create an object with three key/value pairs. We then use the Object.keys() method to get an array of the object's keys. The output is an array containing the keys "name", "age", and "city". We can also use the bracket notation to access the keys of an object. This is useful if the key is stored in a variable.
index.js
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const key = 'name';
console.log(person[key]);
// Output: 'John'
In the example above, we create an object with three key/value pairs. We then create a variable called "key" and assign it the value "name". We can then use the bracket notation to access the value associated with the "name" key. The output is the string "John".

Object Values

In JavaScript, an object is a collection of key-value pairs. The values can be of any type, including numbers, strings, booleans, arrays, functions, and even other objects. The key is a unique identifier.

Values can be accessed and modified using dot notation or bracket notation. Dot notation is used when the key is a valid JavaScript identifier. Bracket notation is used when the key is not a valid JavaScript identifier or when the key is a number.

Let's look at an example of how to access and modify object values.

index.js
const person = {
  name: 'John',
  age: 30
};

console.log(person.name); // 'John'
console.log(person['age']); // 30

person.name = 'Bob';
person['age'] = 40;

console.log(person.name); // 'Bob'
console.log(person['age']); // 40

In the example above, we access the name and age values of the person object using dot notation and bracket notation. We then modify the name and age values using the same notation.

We can also add new properties to an object using the same notation.

index.js
const person = {
  name: 'John',
  age: 30
};

person.city = 'New York';

console.log(person.city); // 'New York'

In the example above, we add a city property to the person object using dot notation.

Object Entries

Objects are a fundamental concept in JavaScript and are used to store collections of data. An object is a collection of key-value pairs, where each key is unique and the value can be any data type. Object entries are a way to access each key-value pair in an object. Object entries are iterable and can be looped over using the for...of statement. To access object entries, you can use the Object.entries() method. This method returns an array of the object's enumerable properties, in the same order as that provided by a for...in loop. The array is an array of arrays where each inner array is a key-value pair.
index.js
const obj = {
  name: 'John',
  age: 30
};

for (const [key, value] of Object.entries(obj)) {
  console.log(key + ': ' + value);
}
// Output:
// name: John
// age: 30
The example above shows how to use the Object.entries() method to access the object entries of an object. The result of the Object.entries() method is an array of arrays, where each inner array is a key-value pair. The for...of loop is used to iterate over the array and access each key-value pair.

Object Assign

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying propertied definitions, including their enumerable and non-enumerable flags, see Object.getOwnPropertyDescriptor and Object.defineProperties.

Syntax:
Object.assign(target, ...sources)
Parameters:
  • target - The target object.
  • sources - The source object(s).

Example:
index.js
const object1 = {
  a: 1,
  b: 2,
};

const object2 = {
  b: 4,
  c: 5,
};

const object3 = Object.assign(object1, object2);

console.log(object3);

Output:
{ a: 1, b: 2, c: 3 }

Object Create

Object creation in JavaScript is an important concept to understand. Objects are the foundation of JavaScript and provide a way to store and access data. Objects are created using the object constructor and can be modified using various methods.

The object constructor is used to create new objects. In JavaScript, the object constructor is a function that returns a new object. The object constructor takes a set of key-value pairs as arguments and creates an object from them. The key-value pairs are used to define the properties and values of the new object.

Objects can be modified using various methods. The most common way to modify an object is to add or remove properties. Properties can be added to an object using the dot notation or the square bracket notation. The dot notation is used to access the property of an object and the square bracket notation is used to access the value of a property.

Objects can also be modified using the delete operator. The delete operator is used to delete a property from an object. It is important to note that the delete operator does not delete the object itself, only the property of the object.

Objects can also be modified using the Object.assign() method. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It is important to note that the Object.assign() method does not copy the properties of the source object, only the values.

Objects can also be modified using the Object.freeze() method. The Object.freeze() method is used to freeze an object, which means that the object cannot be modified. The Object.freeze() method is used to prevent accidental modification of an object.

Objects can also be modified using the Object.seal() method. The Object.seal() method is used to seal an object, which means that the object cannot be modified or deleted. The Object.seal() method is used to prevent accidental modification or deletion of an object.

Objects can also be modified using the Object.defineProperty() method. The Object.defineProperty() method is used to define a new property on an object or modify an existing property on an object. The Object.defineProperty() method is used to define the properties of an object and to control how the properties are accessed.

Objects can also be modified using the Object.defineProperties() method. The Object.defineProperties() method is used to define multiple properties on an object or modify existing properties on an object. The Object.defineProperties() method is used to define multiple properties on an object and to control how the properties are accessed.

Objects can also be modified using the Object.create() method. The Object.create() method is used to create a new object with the specified prototype object and properties. The Object.create() method is used to create an object with the specified prototype object and properties.

Objects can also be modified using the Object.getOwnPropertyDescriptor() method. The Object.getOwnPropertyDescriptor() method is used to get the property descriptor of an object. The Object.getOwnPropertyDescriptor() method is used to get the property descriptor of an object and to control how the property is accessed.

Example:

index.js
const person = Object.create({
  name: 'John',
  age: 25
});

person.name = 'Jane';
person.age = 30;

console.log(person.name); // 'Jane'
console.log(person.age); // 30

Object Define Property

The Object.defineProperty() method is used to define a new property directly on an object, or modify an existing property on an object, and return the object.
Syntax: Object.defineProperty(obj, prop, descriptor)
Parameters:
  • obj: The object on which to define the property.
  • prop: The name of the property to be defined or modified.
  • descriptor: The descriptor for the property being defined or modified.

Example:

index.js
const person = {
  name: 'John Doe'
};

Object.defineProperty(person, 'age', {
  value: 20,
  writable: false,
  enumerable: true,
  configurable: false
});

console.log(person);

Object Define Properties

Objects in JavaScript are collections of key/value pairs. They are used to represent real-world objects, such as users, products, and so on. The Object.defineProperty() method is used to add a single property to an object, or to modify the attributes of an existing property of an object. The syntax for Object.defineProperty() is as follows:
index.js
Object.defineProperty(object, property, descriptor)
The first argument of Object.defineProperty() is the object on which to define the property. The second argument is the name of the property to be defined or modified. The third argument is an object that specifies the descriptor for the property being defined or modified. The descriptor object can have the following properties:
  • configurable: This property specifies whether or not the property can be deleted or modified. It is a Boolean value. The default value is false.
  • enumerable: This property specifies whether or not the property can be enumerated in a for-in loop. It is a Boolean value. The default value is false.
  • value: This property specifies the value associated with the property. It can be any valid JavaScript value (number, object, function, etc). The default value is undefined.
  • writable: This property specifies whether or not the property can be modified. It is a Boolean value. The default value is false.
  • get: This property specifies a function that will be called when the property is accessed. The default value is undefined.
  • set: This property specifies a function that will be called when the property is modified. The default value is undefined.
Here is an example of using Object.defineProperty() to add a property to an object:
index.js
let user = {};
Object.defineProperty(user, 'name', {
  value: 'John',
  writable: true,
  configurable: true
});
In the above example, we have added a property named “name” to the object “user”. The value of the property is “John”. We have also specified that the property is writable and configurable. Here is an example of using Object.defineProperty() to modify an existing property of an object:
index.js
let user = {
  name: 'John'
};
Object.defineProperty(user, 'name', {
  value: 'John Doe',
  writable: false
});
In the above example, we have modified the property “name” of the object “user”. We have changed the value of the property to “John Doe” and we have set the property to be non-writable.