I am trying to separate the logic of my application by using multiple javascript files that focus on certain specific tasks.
The functions defined within the JSfiles need to be accessed between the files themselves.
I understand that the order of calling the functions is important and defining “global” vs “local” scope is important. In the following files the files are not wrapped in functions so I suppose they are in the global scope.
file1.js
function addingToDOM(stuff) {
...
...
}
file2.js
// call addingToDOM
addingToDOM(someStuff);
function doOtherTHings() {
...
...
}
HTML (order of files)
<script src="file1.js"></script>
<script src="file2.js"></script>
ERROR
addingToDOM is not defined
file2.js calls file1.js after file1.js in the HTML.
I don’t understand why it’s not defined.
Your JS files should just define functions and call ones that are in the same JS file. If you’re going to call functions in a JS file from another, that JS file needs to be loaded first. I would put all the calling code (kind of like your “main” function in other languages like C) in one place, preferably at the end of your html document. After all, the other JS files (and the markup) is loaded. It’s not that you can’t call a function in file1 from file2, it’s that they should both be fully loaded before your code begins to run.
Your setup should work as it is, but be sure to call the first function that needs to be run not from within a JS file, but at the end of your HTML document.