JavaScript - Executing a function from an external JS file

How can I invoke a function located in a JavaScript file that I’ve imported into my project? Suppose I have a file named ‘utils.js’ with a function called ‘calculateSum’. I’d like to call ‘calculateSum’ from another JavaScript file. Could someone provide guidance or a code example on how to achieve this? For more understanding, consider looking into how JavaScript modules work.

Hey there,

Import calculateSum from utils.js like this:

import { calculateSum } from './utils.js';

calculateSum();

Hey, what’s up? :blush: Imagine you’ve got a handy function called calculateSum in a file named utils.js, and you wanna use it in another script. No worries, it’s pretty straightforward! Here’s how you can do it using JavaScript ES6 modules:

First, make sure your utils.js file looks something like this:

// utils.js
export function calculateSum(a, b) {
  return a + b;
}

With that done, you can bring it into your main file like this:

// main.js
import { calculateSum } from './utils.js';

const result = calculateSum(3, 4);
console.log(result); // Outputs: 7

Remember to use export in your utils.js and import in your main.js. It’s like sharing a cool hobby with a friend—simple and fun! Let me know if you run into any hiccups!