How To Call One Method From Another In Javascript

In this tutorial, we will explore how to call one method from another in JavaScript. This is particularly useful when you want to reuse the functionality of a method inside another method without having to write the same code again.

By having a clear understanding of this concept, you can make your JavaScript code more efficient and maintainable.

Step 1: Understanding Functions and Methods in JavaScript

Before we dive into the main concept of this tutorial, let’s have a quick overview of what functions and methods are in JavaScript.

A function in JavaScript is a named set of instructions wrapped between curly braces {} that are used to perform a specific task. Functions can be defined using the function keyword, followed by a name and the arguments required for its execution inside parentheses (). Functions can return a value using the return statement.

On the other hand, a method is a function that is assigned to an object’s properties. In other words, methods are functions that belong to an object and can be called using the object’s property.

Step 2: Defining Two Methods

Let’s define two methods for demonstration purposes. First, we will define a method named printMessage that simply prints a message to the console. Then, we will define another method called callPrintMessage that will call the printMessage method.

In the above code block, we have defined an object obj with two methods: printMessage and callPrintMessage. Notice the use of the this keyword inside the callPrintMessage method to reference the object’s properties and methods.

Step 3: Calling One Method from Another

Now that our methods are defined, let’s see how to call the printMessage method from inside the callPrintMessage method:

The output will be:

Hello, World!

In this example, we have called the printMessage method using the this keyword followed by the method’s name and the required arguments.

Conclusion

In this tutorial, we learned how to call one method from another in JavaScript by using the this keyword to reference the object and its properties. This approach allows for better code reusability and a more organized structure, making it easier to maintain and debug your JavaScript code.

Here is the full code from the tutorial: