Method
A method refers to a function that belongs to an object
.
This means having a function as a property of an object.
Basic data types such as strings, arrays, and numbers are also treated as objects, which means methods can be used on these data types as well.
Below is an example of methods used to manipulate string data.
let name = 'banana';
// Method that returns the length of the string
console.log(name.length); // 6
// Method that converts the string to uppercase
console.log(name.toUpperCase()); // BANANA
Using the .length
method on a string returns the length of the string.
The .toUpperCase()
method converts all characters in the string to uppercase.
Difference Between Methods and Functions
Functions are independent blocks of code that perform specific tasks as a code set.
Functions are not bound to any particular object and can be called from anywhere.
function greet() {
console.log('Hello!');
}
greet(); // Hello!
In contrast, methods are functions that exist as properties of an object.
To use values within an object, you use the this
keyword, where this
refers to the object the method belongs to.
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.