Calling a Function present in one Js File in Another Js File

I want to make a program where a function in a ‘.js’ file is supposed to be called in a second ‘.js’ file. I have tried exporting and importing ‘functions’ but they don’t work. Is there any simple way to do the thing just using Javascript and or not jQuery without going the complicated way of using React.js or others?

Yes, you can call a function from one .js file in another .js file using the export and import statements in JavaScript. Here’s an example:

functions.js:

export function add(a, b) {
  return a + b;
}

main.js :

import { add } from './functions.js';

console.log(add(1, 2)); // Output: 3

In the functions.js file, we’ve defined a function called add and used the export statement to make it available for use in other files. In the main.js file, we’ve used the import statement to import the add function from the functions.js file and then called it with the values 1 and 2.

Make sure that the import and export statements are at the top level of your JavaScript files and that you include the file extension (e.g., .js) when specifying the file path in the import statement.

1 Like

Thank you for the suggestion. It helps me!

Yes, you can use the CommonJS module system to export and import functions between JavaScript files. CommonJS is a standard module system used in Node.js, but it can also be used in the browser with tools like Browserify or Webpack.

I want to call fn1() defined in first.js in second.js. From my searches answers were if first.js is defined first it is possible, but from my tests I haven’t found any way to do that.

Here is my code:

second.js

document.getElementById("btn").onclick = function() {
    fn1();
}

first.js

function fn1() {
    alert("external fn clicked");
}
 @himanshu.arya @aditya2010.kadiyala

@chethankumaram5627

The error of Cross-Origin Requests are blocked by CORS policy (check console (RightClick + Inspect or F12) for error message) occurs because the browser blocks all of the cross-origin requests, even local files on the system as long as the HTML code is running as a local file. To fix this error, you need to

  • Either host your file
  • Or run a development server

You can host your file by clicking or navigating to the following website to freely host sites (static):

Hostatic: Freely host static files

Or by creating a dynamic website in React.js which runs in a dev server, and typing the following code:

In second.js:

import fn1 from '//Wherever you file is located';

document.getElementById("btn").onclick = () => {
    fn1();
}

In first.js:

const fn1 = () => {
   console.log("Clicked Button!");
}

PS: Also try to use console.log() instead of alert() since it is where you can see the errors as well as responses from the site.