Start Coding

Topics

JavaScript Objects

JavaScript objects are fundamental data structures that allow you to store and organize related data and functionality. They are collections of key-value pairs, where each key is a unique identifier for a property or method.

Creating Objects

There are multiple ways to create objects in JavaScript. The most common methods are object literals and the constructor function.

Object Literals

Object literals provide a simple and concise way to create objects:


const person = {
    name: "John Doe",
    age: 30,
    greet: function() {
        console.log("Hello!");
    }
};
    

Constructor Function

Constructor functions allow you to create multiple objects with the same structure:


function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log("Hello, I'm " + this.name);
    };
}

const john = new Person("John Doe", 30);
    

Accessing Object Properties

You can access object properties using dot notation or bracket notation:


console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation
    

Object Methods

Methods are functions stored as object properties. They can access and manipulate the object's data:


const calculator = {
    add: function(a, b) {
        return a + b;
    },
    subtract: function(a, b) {
        return a - b;
    }
};

console.log(calculator.add(5, 3)); // Output: 8
    

Object Prototypes

Prototypes allow objects to inherit properties and methods from other objects. This concept is crucial for understanding JavaScript's object-oriented programming model. Learn more about JavaScript Prototypes.

Important Considerations

  • Objects are reference types, meaning variables store references to objects rather than the objects themselves.
  • Use the delete operator to remove properties from objects.
  • The Object.keys() method returns an array of an object's enumerable property names.
  • To prevent modifications to an object, use Object.freeze().

Related Concepts

To deepen your understanding of JavaScript objects, explore these related topics:

By mastering JavaScript objects, you'll be well-equipped to create more complex and organized code structures in your applications.