Call function from one JS file into another JS file in JavaScript

This tutorial will show you how to call a function from one JavaScript file into another Javascript file.

First, I will create a button in HTML to show the result in browser.

<input type = "button" value = "Show the result" onclick = "codeSpeedy()"/>

In the above HTML program, I have created a button called Show the result which needs to be clicked by the user to see the result.

Here’s the first JavaScript program ( index1.js)

let num1 = 7;
let num2 = 5;

function result() {
    return num1 * num2;
}

Here I have declared two variables num1 & num2  and assigned the value of num1 is 7 and num2 is 5. Then the function result()that will return the multiplication of num1 and num2 whenever we call the function.

Here’s the second JavaScript program ( index2.js)

function codeSpeedy() {
    document.write((result()).toFixed());
}

The document.write() method used to write the output in the browser.

Then I called the result() function from the index1.js to calculate the result.

And toFixed() method to convert the number into a string and print the string.

Now, I have to insert these two Javascript files in the above HTML program that I created first like below.

<body>
    <input type = "button" value = "Show the result" onclick = "codeSpeedy()"/>

    <script src="index1.js"></script>
    <script src="index2.js"></script>
</body>

If you run this program, you will get a Show the result button, as soon as you click the button the function codeSpeedy() will execute and will display the calculated result in the browser.

Output:

35

Notes:

  • toFixed() method rounds off a number to a significant number of decimal.

Leave a Reply

Your email address will not be published. Required fields are marked *