Free lesson · JavaScript Basic to Advance
Object Methods and Shorthand Syntax
What Is a Method?
A method is a function that lives as a property of an object. From a language perspective, there's no special "method" type — it's just a function stored as a property. But methods have a useful property: when you call them as obj.method(), the this keyword inside the function refers to the object the method was called on.
const user = {
name: "Olena",
age: 35,
greet: function() {
return `Hi, I'm ${this.name}`;
},
birthday: function() {
this.age = this.age + 1;
return this.age;
}
};
console.log(user.greet()); // "Hi, I'm Olena"
console.log(user.birthday()); // 36
console.log(user.age); // 36 — modified by the method
The greet and birthday functions are methods on the user object. Inside them, this refers to user. This is how methods can read and modify the object they belong to without needing the object passed as a parameter.
We cover this in detail in Module 8 — there's a lot more to it than this Topic shows, including the gotchas. But for now, the basic pattern of "methods use this to refer to their object" is what you need.
Interactive animation: this is the object before the dot - one function on two objects gives two answers.
Method Shorthand Syntax
Modern JavaScript provides a shorthand syntax for defining methods inside object literals:
// Old verbose syntax
const userOld = {
name: "Olena",
greet: function() {
return `Hi, I'm ${this.name}`;
}
};
// Modern shorthand
const user = {
name: "Olena",
greet() { // no 'function' keyword, no colon
return `Hi, I'm ${this.name}`;
}
};
console.log(userOld.greet());
console.log(user.greet());
Both objects are functionally identical. The shorthand version is shorter and more common in modern code. You'll see both forms in real codebases — old code uses the verbose form, new code uses the shorthand.
The two forms aren't entirely equivalent at the spec level (the shorthand version produces a slightly different internal function definition with respect to super calls and a few edge cases), but for everyday code, treat them as the same.
Arrow Functions in Objects — Be Careful
Recall from Topic 5.3: arrow functions don't have their own this. They inherit this from the surrounding scope. This makes them problematic as object methods:
const user = {
name: "Olena",
greetTraditional: function() {
return `Hi, I'm ${this.name}`;
},
greetMethod() {
return `Hi, I'm ${this.name}`;
},
greetArrow: () => {
return `Hi, I'm ${this.name}`;
}
};
console.log(user.greetTraditional()); // "Hi, I'm Olena"
console.log(user.greetMethod()); // "Hi, I'm Olena"
console.log(user.greetArrow()); // "Hi, I'm undefined"
The greetArrow method doesn't work. Inside it, this doesn't refer to user — it refers to whatever this was in the surrounding scope (usually the global object or undefined). Arrow functions are the wrong choice for object methods that need this.
The rule: use shorthand methods or traditional function expressions for methods that need this. Don't use arrow functions as object methods unless you specifically want the this-inheriting behavior.
When would you use an arrow function as a method? In rare cases where you specifically want to capture the outer this. This is mostly an issue in class methods that use callbacks — covered in Module 8.
Interactive animation: Arrow as a method, no - arrow inside a method, yes, where it inherits the method's this.
Methods That Return the Object: Method Chaining
A pattern you'll see in real code: methods that return their own object, enabling chained calls.
const builder = {
result: "",
add(text) {
this.result += text;
return this; // returns the builder, so we can chain
},
upper() {
this.result = this.result.toUpperCase();
return this;
},
done() {
return this.result;
}
};
const message = builder
.add("Hello, ")
.add("Olena!")
.upper()
.done();
console.log(message);
Each method that modifies the object returns this. That lets you chain calls together — builder.add(...).add(...).upper() works because each call returns the builder for the next one to use.
This is the "fluent interface" pattern. You see it in libraries like jQuery, in the array methods .map().filter().reduce(), and in many builder patterns. Returning this is the trick that makes it work.
graph LR
A[builder.add] -->|returns this| B[builder.add]
B -->|returns this| C[builder.upper]
C -->|returns this| D[builder.done]
D -->|returns result| E[Final string]
style A fill:#7c3aed,color:#fff
style B fill:#7c3aed,color:#fff
style C fill:#7c3aed,color:#fff
style D fill:#10b981,color:#fff
This diagram shows method chaining. Each method on the builder object returns this — a reference to the builder itself. That allows the next method in the chain to be called on the same object. The chain continues until you reach a method like done that returns a final value instead of this, ending the chain and producing the result.
Getters and Setters
Objects can have getter and setter methods that look like properties when accessed.
const user = {
firstName: "Olena",
lastName: "Marchenko",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
const parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
console.log(user.fullName); // "Olena Marchenko" — looks like a property read
user.fullName = "Nikhil Joshi"; // looks like a property write
console.log(user.firstName); // "Nikhil"
console.log(user.lastName); // "Joshi"
fullName looks like a property, but it's actually two methods — one for reading (the getter, called when user.fullName is read) and one for writing (the setter, called when user.fullName = ... is assigned). The syntax get and set before the method name distinguishes them.
Getters and setters are useful for:
- Computed properties —
fullNamederived fromfirstNameandlastName - Validation — a setter that checks values before storing them
- Lazy evaluation — a getter that computes its value the first time it's accessed
- Backward compatibility — exposing a new computed property as if it were a real one
They're not used everywhere, but they're a useful tool when computed access matters. Modern classes (Module 8) use them frequently.
Interactive animation: A computed property with a plain-property face - read without parentheses, its getter runs on every read.
The this Question, Briefly
Throughout this Topic, methods have been using this to refer to the object they're called on. This works because of one specific rule: when you call a function with the syntax obj.method(), JavaScript sets this inside the method to obj.
But that rule is more subtle than it looks. Calling the same function in different ways produces different values of this. We cover this in detail in Module 8 — it's one of the most-confused topics in JavaScript. For Module 7, just know:
obj.method()→thisisobj- Arrow functions don't have their own
this— they inherit from the surrounding scope - Methods that lose their object context (passed as callbacks, stored in variables) lose their
this
The third one is a common bug:
const user = {
name: "Olena",
greet() {
return `Hi, I'm ${this.name}`;
}
};
console.log(user.greet()); // "Hi, I'm Olena"
const detached = user.greet;
console.log(detached()); // "Hi, I'm undefined" (or throws in strict mode)
When greet is stored in detached and called without an object, there's no object to be this. The method appears broken. The full explanation is in Module 8 — but be aware of this pattern when you see methods being passed around.
Interactive animation: Find the call, find the dot - four ways of calling, traced to the this each one gets.
Common Pitfalls
Warning: The method traps.
Using arrow functions as methods that need
this. Arrow functions inheritthisfrom the surrounding scope, which usually isn't your object. Use shorthand methods or traditional function syntax.Losing
thisby detaching methods. Storingobj.methodin a variable and calling that variable loses the binding. This is the source of many "why is thisundefined" bugs.Confusing methods with regular functions. A method is just a function stored as a property. There's no special method type. The "method" behavior is purely about how the function is called.
Why This Matters in Interviews
Interview: Method-related interview questions usually come in two forms. First: "What's the difference between an arrow function and a regular function as a method?" The answer involves
thisbinding. Second: "Why does this code not work?" — followed by code where a method has been detached or wrapped, breaking thethisbinding.Method shorthand syntax is expected fluency in modern JavaScript. Using
greet: function() {}instead ofgreet()signals stale code style.Topic 7.8 — Interview Lens: Objects and Prototypes — covers the deeper interview treatment.
Try It
Exercise: Build a "playlist" object with these properties:
- A
songsarray- An
add(song)method that appends to the array and returnsthisfor chaining- A
remove(song)method that filters the array and returnsthis- A
play()method that logs which song is playing (the first one) and returnsthis- A
countgetter that returns the number of songsUse shorthand method syntax for all of them. Then call them in a chain:
const playlist = { // your code }; playlist .add("Song A") .add("Song B") .add("Song C") .play(); console.log(playlist.count);Once it works, try assigning one of the methods to a variable and calling it standalone — see what happens when
thisis lost.