Javascript Object

In JavaScript, an object is a collection of key-value pairs, where the keys are strings (also called properties or attributes), and the values can be any valid JavaScript data type, including other objects, arrays, functions, and primitive data types such as numbers and strings. Objects are one of the fundamental data types in JavaScript and are used extensively in the language to represent data and functionality.

In JavaScript, objects can be created using object literals, which are enclosed in curly braces `{}`, like this:

// JavaScript Object {} code example
const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  }
};
          

In the above example, `person` is an object with three properties: `name`, `age`, and `address`. The `address` property is itself an object with three properties: `street`, `city`, and `state`.

Objects can also be created using the `Object()` constructor, like this:

// JavaScript new Object() code example
const person = new Object();
person.name = 'John';
person.age = 30;
person.address = {
  street: '123 Main St',
  city: 'New York',
  state: 'NY'
};
          

In addition to adding properties to objects, you can also access and modify the properties of an object using dot notation or bracket notation. For example:

Example for accessing values of an object

const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  }
};

alert(person.name); // Output: 'John'
alert(person['age']); // Output: 30
          

Example of modifying values of an object

const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  }
};
person.name = 'Jane';
person['age'] = 35;

alert(person.name); // Output: 'Jane'
alert(person.age); // Output: 35
          

Objects in JavaScript are dynamic, which means that you can add or remove properties from an object at any time. Objects can also be used to represent complex data structures, such as trees and graphs, and to encapsulate data and behavior in object-oriented programming.

Conclusion

In summary, objects are a fundamental data type in JavaScript that allow you to represent collections of key-value pairs. An object is defined by a set of properties, where each property is identified by a unique key and has a corresponding value. Objects can contain properties that are themselves objects, allowing you to represent complex data structures.

You can create objects using object literals or the Object constructor, and you can access and modify properties using dot notation or bracket notation. Objects are dynamic and can be modified at any time, making them a powerful tool for representing and manipulating data in JavaScript.

Now challenge yourself, click the link below to practice!

  • https://codepen.io/pen/
  • Are you ready to take a quiz now?

  • Start Quiz Now