Method
In JavaScript, objects can have properties and methods. A method is simply "a function of the object".
Let's look at several examples of methods for handling strings (length, toUpperCase).
length, toUpperCase Method Examples
let name = 'banana';
// A method that returns the length of the string
console.log(name.length); // 6
// A method that converts the string to uppercase
console.log(name.toUpperCase()); // BANANA
These methods can be defined not only for primitive data types but also for user-defined objects.
2. Differences between Methods and Functions:
Function:
- A function is an independent block of code. It is a set of instructions that perform a specific task.
- Functions are not bound to any particular object.
-
Function Example
function greet() {
console.log('Hello!');
}
greet(); // Hello!
Method:
- A method is a function defined as a property of an object.
- Methods are called within the context of the corresponding object and often access other properties of the object.
- Use the
this
keyword to refer to the object within a method. Here,this
refers to the object that owns the method. -
Method Example
const person = {
name: 'John',
greet: function () {
console.log('Hello, ' + this.name + '!');
},
};
person.greet(); // Hello, John!
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.