From this exercise I’d like to understand how is it that we can use the renderRawResponse()
function inside main.js without it being imported from helperFunctions.js:
helperFunctions.js
const renderRawResponse = (res) => {
...
}
main.js
// Asynchronous function
const getSuggestions = () => {
const wordQuery = inputField.value;
const endpoint = `${url}${wordQuery}`;
fetch(endpoint, {cache: 'no-cache'})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message)
})
.then( jsonResponse => {
renderRawResponse(jsonResponse); // This function has not been imported into main.js
});
}
1 Like
These are all “run” because they’re in the HTML file (index.html
)
close to the end, it has:
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="public/main.js"></script>
<script src="public/helperFunctions.js"></script>
The first one loads or runs jQuery. So any scripts afterward have access to any global variables or functions created by running the code in this JavaScript file.
The second one loads the JavaScript code in the file main.js, so any script that runs afterward still has the global variables created by running this code.
After this, the code in helperFunctions.js is loaded and some of that runs too, having access to any global variables created previously.
Later,
getSuggestions
in main.js is called when some event happens (possibly a button being clicked)
and stuff in getSuggestions
calls renderRawResponse
, which still exists as a function or variable in global scope (created earlier).
2 Likes
Got it, the function is within the call stack, then gets called on a given event.
Mixed some JS modules logic for a second.
Thanks for clearing it out!