Object Methods & Properties – JavaScript Tutorial
JavaScript constructor function for creating person objects
In JavaScript, objects are used to store related data and functionalities. Understanding object properties and methods is essential for writing efficient and maintainable code.
In this tutorial, we'll explore how to define, access, and use properties and methods inside JavaScript objects.
Object properties are values associated with a JavaScript object. Each property is a key-value pair.
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
firstName
, lastName
, and age
are keys (or property names).
Their corresponding values are "John", "Doe", and 30.
You can access properties using:
Dot notation
console.log(person.firstName); // John
Bracket notation
console.log(person["lastName"]); // Doe
person.gender = "male";
person.age = 31;
delete person.lastName;
Object methods are functions stored as object properties. They allow objects to perform actions.
const person = {
firstName: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.firstName);
}
};
person.greet(); // Output: Hello, my name is John
greet
is a method of the person
object.
The this
keyword refers to the object it belongs to.
You can define methods in a shorter syntax:
const user = {
name: "Alice",
sayHi() {
console.log("Hi, I'm " + this.name);
}
};
user.sayHi(); // Output: Hi, I'm Alice
Objects can contain other objects and methods:
const company = {
name: "Tech Corp",
employee: {
name: "Emma",
role: "Developer",
introduce() {
console.log("I'm " + this.name + ", a " + this.role);
}
}
};
company.employee.introduce(); // Output: I'm Emma, a Developer
Calculating values
Handling events in web applications
Validating data
Updating internal state
const user = {
birthYear: 1995,
getAge(currentYear) {
return currentYear - this.birthYear;
}
};
console.log(user.getAge(2025)); // Output: 30
JavaScript objects become more powerful when you understand how to work with properties and methods. By mastering these basics, you’re setting a solid foundation for working with object-oriented programming, APIs, and modern JavaScript frameworks.
In the next tutorials, we'll cover object destructuring, prototypes, and classes.
Happy coding! 🚀