JavaScript Requests

This question is targeted, specifically to this exercise example.

In step 8 it instructs to call renderRawResponse which is a helper function declared in another file - helperFunction.js. Why is there no reference to importing it. Can the function object just be called like without importing if it’s within the same file directory? Or has this been omitted to solely focus on the overall objective of the lesson of learning to make AJAX requests?

You’ll find this code inside the index.html file:

  <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>

Because the helperFunctions.js file has been linked here, the JavaScript in the file is accessible. I’m sure someone else could give you a more descriptive answer, but this is essentially why.

Hi coursecoder32047,
As already mentioned by @midlindner, main.js and helperFunctions.js files are linked to html page. When page loads, It loads the js files. The file coming after another js files can access methods or variables from it as all these methods and variables are globally available to them. This is a not a good thing (for a big app but works fine here) to have as It can create certain problems - like Global name space pollution, Name collisions etc.

Previously we used few patterns to avoid it -
1.Using Object to avoid namespace collision
2.Use of IIFE

Now we have some modern solutions where if variables and methods are not explicitly shared then it can’t be accessed by other js fle. Each file live in their own “land”. Few of the solutions are -

  • Es6 module system (Famously used in React) - Here you import and export stuffs.

  • CommonJs module system (Famously used in Node) - Here you export and require stuffs.

Hope it helps.

1 Like