- Abstraction
- AI Pair Programming
- Algorithm
- API
- Array
- Array methods
- Booleans
- Callback
- Class
- Class Members
- Closure
- Closure
- Code refactoring
- Comment
- Computer programming
- Conditional statements
- Constant
- Constructor
- Coupling and Cohesion
- Data types
- Debugging
- Decorator
- Dependency
- Destructuring
- Dictionary
- Enum
- Event
- Exception / Error handling
- Function
- Generic / Template
- Higher-order function
- IDE
- Immutability
- Inheritance
- Input validation
- Integer
- Interface
- Iteration patterns
- Legacy code
- Loop
- Machine learning
- Memoization
- Memory and references
- Method
- Module
- Null / Undefined / None
- Null safety / Optional values
- Object
- Object-Oriented Programming (OOP)
- Operator
- Parameter
- Parsing
- Promise and Async/Await
- Prompt Engineering
- Recursion
- Regular expression
- Return statement
- Rollback
- Runtime
- Scope
- Script
- Sequence
- Set
- Spaghetti code
- Spread and Rest operators
- State management
- String
- Switch statement
- Synchronous vs Asynchronous execution
- Syntax
- Technical debt
- Ternary operator
- Testing
- This / Self
- Tuple
- Type casting
- Type conversion
- Variable
- Vibe coding
- Webhook
PROGRAMMING-CONCEPTS
Method: Definition, Purpose, and Examples
A method is a function that belongs to an object. It defines what that object can do—its behavior—and often works with the data stored inside the object. Methods make programs more organized by grouping actions with the data they act upon, forming one of the key ideas behind object-oriented programming.
When you call a method, you’re usually telling an object to perform an operation on itself. For example, in Python, the expression "hello".upper() uses the string’s built-in upper() method to return a capitalized version of that string.
What Makes a Method
Every method is just a function, but one that’s attached to an object or class. This means it always has access to the object’s internal data. In object-oriented programming, this connection between data and behavior is what gives code its structure and clarity.
In Python, for instance, methods are defined inside classes and always take self as their first parameter. That parameter represents the instance the method belongs to.
Python
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
buddy = Dog("Buddy")
buddy.bark()
Here, bark() is a method, not a standalone function. It uses the object’s own data (self.name) to produce output.
In JavaScript or TypeScript, methods are defined inside objects or classes in a similar way:
class Dog {
constructor(private name: string) {}
bark() {
console.log(`${this.name} says woof!`);
}
}
const buddy = new Dog("Buddy");
buddy.bark();
The this keyword in JavaScript and TypeScript serves the same purpose as self in Python—it refers to the current instance.
Methods vs. Functions
Although they share syntax and behavior, methods and functions serve different roles. A function stands alone—it performs a task independently. A method is tied to a specific object or class and often modifies or interacts with that object’s internal state.
Think of it this way: a function is like a tool anyone can use, while a method is a tool designed for a particular machine. You can call len("text") in Python as a general function, but "text".upper() is a method specifically for string objects.
In JavaScript, you might use a function like Math.max(2, 5, 8)—that’s a standalone function within the global Math object—but an array’s .push() method, as in [1, 2].push(3), belongs only to arrays.
Instance Methods, Class Methods, and Static Methods
Most methods you write are instance methods, meaning they belong to a specific object created from a class. But there are other types of methods that serve different purposes.
In Python, class methods act on the class itself, not on a single instance. They’re marked with the @classmethod decorator.
Python
class Circle:
def __init__(self, radius):
self.radius = radius
@classmethod
def unit_circle(cls):
return cls(1)
Here, unit_circle() creates a circle with radius 1—without requiring an existing object first.
Static methods, marked with @staticmethod, don’t need access to either the instance or the class. They behave more like regular functions but still live inside the class for logical grouping.
Python
class MathHelper:
@staticmethod
def add(a, b):
return a + b
In Swift, you can define similar behavior using static func or class func:
class MathHelper {
static func add(a: Int, b: Int) -> Int {
return a + b
}
}
TypeScript and JavaScript also support static methods:
class MathHelper {
static add(a: number, b: number): number {
return a + b;
}
}
These methods are called directly on the class, not on instances, as in MathHelper.add(2, 3).
Built-in Methods
Many data types come with prebuilt methods that make working with them easier. In Python, lists, strings, and dictionaries each have dozens of methods that perform useful operations.
For example:
Python
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # [1, 2, 3, 4]
The append() method modifies the list directly.
In JavaScript, arrays and strings behave similarly:
const names = ["Luna", "Milo"];
names.push("Nova");
console.log(names); // ["Luna", "Milo", "Nova"]
Here, .push() is a method belonging to the Array prototype, and it modifies the array it’s called on.
Methods give data objects functionality, so you don’t have to manipulate their contents manually.
Methods in React Components
In React, methods are commonly used inside class components or custom hooks to handle user interactions or state updates. While modern React relies mostly on functional components, the concept remains the same: you attach behavior to an object (in this case, a component).
class Counter extends React.Component {
state = { count: 0 };
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<button onClick={() => this.increment()}>
Count: {this.state.count}
</button>
);
}
}
Here, increment() is a method that updates the component’s state whenever the user clicks the button. Even in functional React components, hooks like useState() serve a similar role by associating behavior with data.
Why Methods Matter
Methods help keep code organized and meaningful. By attaching behavior to data, they allow you to express logic in a way that mirrors how people describe actions. Instead of calling a random function like update_balance(account), you can write account.update_balance(). That’s easier to read and intuitively ties the action to the object it affects.
They also make code more reusable. Once you define a method inside a class, every instance of that class automatically inherits the same behavior. If you ever need to change how it works, you update it in one place instead of rewriting it across your codebase.
Common Mistakes with Methods
Beginners often struggle with how methods handle scope and references. In Python, forgetting self inside method definitions leads to errors because the method won’t know which object it belongs to. In JavaScript, methods can lose their this context when passed around as callbacks unless you bind them manually or use arrow functions.
Another common issue is confusing static and instance methods. Instance methods depend on object data, while static ones do not. Mixing the two can lead to design inconsistencies and unexpected behavior.
Best Practices
Good methods are short, descriptive, and focused on one task. They should express what they do clearly—withdraw(), calculate_total(), or send_message() tell you instantly what’s happening. Group related methods logically within a class and keep their access consistent; don’t expose internal helper methods unnecessarily.
Methods should also follow the principle of encapsulation. If a method depends heavily on internal details, it shouldn’t be accessible from outside the class. Keep interfaces clean so that other parts of your program only see what they need to use.
Summary
A method is a function tied to an object or class, defining its behavior and allowing it to interact with its own data. Methods bring structure to programs by connecting actions with the data they modify, supporting the core principles of object-oriented programming.
From Python’s append() and JavaScript’s push() to custom class methods in TypeScript or Swift, methods make code expressive and reusable. By mastering how to design and organize them, you write programs that are not only functional but logical and easy to extend.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.