What's the method to import one JS file into another JS file?

I’m trying to figure out how to bring code from one JavaScript file into another JavaScript file. In CSS we can use something like @import to pull in styles from other stylesheets. Is there a similar way to do this with JavaScript files? I need to access functions and variables from external JS files in my main script. I’ve been searching for the best approach but there seem to be multiple ways to do this. Some people mention using modules while others talk about different loading methods. What’s the most common or recommended way to achieve this? I want to keep my code organized by splitting it into separate files but still be able to use everything together.

Try dynamic imports with import() - they load modules conditionally or on-demand and return a promise. Perfect when you don’t need everything loaded right away. Something like import('./utils.js').then(module => { module.someFunction(); }) only loads when you actually need it. I’ve used this in bigger apps where loading everything upfront kills performance. Works in both browser and Node.js, and you get way more flexibility than static imports. You can even use async/await to make it cleaner.

To import one JavaScript file into another, you generally have two main approaches depending on your environment. If you’re working in a browser, you can leverage ES6 modules. Simply add type="module" to your script tag, then use export in your source file, such as export function myFunction() {}. In your main script, import it like this: import { myFunction } from './myfile.js'. On the other hand, if you’re in a Node.js environment, you would use module.exports in your source file and require() to bring it into your main script. Using ES6 modules is advisable for modern web development due to wider support and better control over your imports. Ensure your file paths are accurate, and keep in mind that module imports run in strict mode by default.

just throw the script tags in your HTML in the right order - works fine. put your functions file first, then main script after. like <script src="helper.js"></script> then <script src="main.js"></script>. old school but perfect for simple projects when you don’t want module syntax.