Wednesday, February 25, 2026

JavaScript Objects (Computer Science and Engineering Notes)

 

JavaScript Objects

Objects are one of the most important concepts in JavaScript. They allow developers to group related data and functionality together, making code more organized and expressive. In JavaScript, an object is essentially a collection of properties (key-value pairs), where values can be data or functions (methods).


🌍 What Is an Object?

  • An object is a standalone entity with properties and type.
  • Properties are associations between a key (string) and a value (any data type).
  • If a property’s value is a function, it is called a method.
    Mozilla Developer
// Example of an object
const person = {
  name: "Alice",
  age: 25,
  greet: function() {
    return `Hello, my name is ${this.name}`;
  }
};

console.log(person.name);   // Alice
console.log(person.greet()); // Hello, my name is Alice

🛠️ Creating Objects

Object Literals

const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020
};

Using new Object()

const book = new Object();
book.title = "1984";
book.author = "George Orwell";

Constructor Functions

function Animal(type) {
  this.type = type;
}
const dog = new Animal("Dog");

Classes

class Student {
  constructor(name, id) {
    this.name = name;
    this.id = id;
  }
}
const s1 = new Student("Bob", 101);

🔄 Object Properties and Methods

  • Accessing properties: object.property or object["property"]
  • Adding properties: object.newProp = value
  • Deleting properties: delete object.prop
  • Methods: Functions stored as property values.
    TutorialsPoint
const phone = {
  brand: "Apple",
  call: function(number) {
    return `Calling ${number}...`;
  }
};

console.log(phone.call("123456789")); // Calling 123456789...

✨ The this Keyword

Inside an object method, this refers to the object itself.

const person = {
  name: "Alice",
  greet: function() {
    return `Hi, I am ${this.name}`;
  }
};
console.log(person.greet()); // Hi, I am Alice

W3School


📊 Comparison Table

FeatureDescriptionExample
Object LiteralQuick way to define an object{name: "Alice"}
Constructor FunctionFunction used to create objectsnew Animal("Dog")
ClassES6 syntax for object blueprintsclass Student {}
MethodFunction inside an objectperson.greet()

📖 Conclusion

JavaScript objects are the backbone of the language, enabling developers to structure data and behavior together. With properties, methods, and flexible creation patterns (literals, constructors, classes), objects make JavaScript powerful and expressive.

No comments:

Post a Comment

Support Vector Machines in Machine Learning

Support Vector Machines in Machine Learning Introduction Support Vector Machines (SVMs) are powerful supervised learning algorithms used ...