JAVASCRIPT Tutorial

Creating JavaScript Objects

Objects are fundamental in JavaScript, allowing you to store and manipulate data in a structured way. Creating objects is straightforward and involves the following steps:

  1. Object Literal:
  • Objects are created using object literals, which are enclosed in curly braces {}.
  • Properties (key-value pairs) represent data stored in the object.
  • Methods (functions) define operations that can be performed on the object.
  1. Properties:
  • Properties assign values to the object.
  • Use property names surrounded by quotes or square brackets.
  • Example: "name": "John"
  1. Methods:
  • Methods are functions defined within the object.
  • Use the syntax: "methodName: function() {...}".
  • Example: "greet": function() { return "Hello, " + this.name; }"
  1. Object Creation:
  • Objects can be created by assigning an object literal to a variable.
  • Example:
const person = {
  name: "John",
  age: 30,
  greet: function() { return "Hello, " + this.name; }
};
  1. Accessing Properties and Methods:
  • Properties are accessed using the dot operator (.).
  • Methods are invoked using the dot operator followed by parentheses ().
  • Example:
console.log(person.name); // Output: John
console.log(person.greet()); // Output: Hello, John

Example:

const employee = {
  name: "Jane Doe",
  salary: 50000,
  promote: function() { this.salary *= 1.1; }
};

employee.promote();
console.log(employee.salary); // Output: 55000

This example demonstrates creating an object with properties (name, salary) and a method (promote) that increases the salary by 10%.