JAVASCRIPT Tutorial

Introduction to Objects

What are Objects?

Objects are data structures that organize data in a structured and meaningful way. They consist of:

  • Key-Value Pairs: Each key is a unique identifier associated with a value.
  • Properties: Values stored in key-value pairs.
  • Methods: Functions that operate on the object's properties.

Practical Steps for Using Objects

  1. Create an Object: Use curly braces ({}) to define an object.
  2. Add Key-Value Pairs: Use the dot (.) or bracket ([]) notation to add properties:
    • object.key = value;
    • object['key'] = value;
  3. Access Properties: Use the dot or bracket notation to access properties:
    • object.key;
    • object['key'];
  4. Add Methods: Use the function keyword to define methods inside the object:
    • object.methodName = function() {...}

JavaScript Example

// Create an object to store person data
const person = {
  name: 'John Doe',
  age: 30,
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

// Access the 'name' property
console.log(person.name); // Output: 'John Doe'

// Call the 'greet' method
person.greet(); // Output: 'Hello, my name is John Doe'

Benefits of Using Objects

  • Organizes data efficiently.
  • Makes it easy to access and modify data.
  • Allows for the creation of complex data structures.