Sometimes, we want to call a JavaScript function in another JavaScript file.
In this article, we’ll look at how to call a JavaScript function in another JavaScript file.
How to call a JavaScript function in another JavaScript file?
To call a JavaScript function in another JavaScript file, we can add script tags.
For instance, we write
<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>
to add script tags.
Then we write
function fn1() {
alert();
}
in 1.js.
Then in 2.js, we write
fn1();
to call fn1
defined in 1.js.
The scripts are run in the order they’re listed so fn1
is defined before it’s called.
Conclusion
To call a JavaScript function in another JavaScript file, we can add script tags.