Will JavaScript modules be executed just once upon importing them?

When a module A is imported inside both module B and C, will the code inside A be executed 2 times in total? For example, if I invoke fetch() within A, will fetch() run twice?

Here's an illustration:

//file: A.js
var A = {
  init: false,
  count: 0
};

if(A.init == false) {
  A.init = true;
  A.value = fetch("https://...");
}

I always thought that module codes are only executed once for the entire lifespan of the webpage regardless of how many times they are imported.

Therefore, if I assign A.count = 1 inside module B, then the value of A.count should also be 1 within module C.

However, as per "Import a module for its side effects only" on:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

I can actually execute the code within module A multiple times for each module (B, C, D) that utilizes it. How does this align with the previous understanding?

Answer №1

Within the code of Module A, it will run twice! First in Module B and then again in Module C.

Module A

function foo() {
  return 'Hey, I am inside Module A being executed in... ';
}

export default foo;

Module B

import foo from './moduleA';

console.log(`${foo()} within Module B`);

Module C

import foo from './moduleA';

console.log(`${foo()} within Module C`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

Encountering issues with the functionality of the MUI Select component, causing the application to crash during

The issue has been successfully resolved I have been in the process of constructing a modal that includes a form and incorporating the MUI Select component. However, upon opening the modal, the application encounters an error; removing the Select componen ...

Using the `on` method of jQuery to make an Ajax request

I'm facing a challenge with using Jquery to load dynamic wall posts for followers. The issue arises when trying to work with dynamic content in the traditional click method. To solve this, I have implemented the on method for the response. However, I ...

Struggling with your Dropdown Menu onclick functionality in Javascript? Let me lend

I am seeking assistance with implementing a Javascript onclick Dropdown Menu. The current issue I am facing is that when one menu is opened and another menu is clicked, the previous menu remains open. My desired solution is to have the previously open menu ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Load information into array for jqGrid display

I am attempting to populate my JQgrid with data every time I click the "1" button, but I am encountering difficulties. As a newbie in jQuery, I am able to display the data in a p tag without any issues. Currently, I am considering whether to use push or a ...

What is the best way to remove text messages from a channel that only allows images?

I have developed a Discord bot named YES with a specific text channel for images only. My goal is to program the bot to automatically delete any text messages in this channel and respond with "You cannot send text messages." However, I also want to create ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage. Although I attempted to utilize mergeMap for this task, I kept encountering the following error ...

The altered variable refuses to show up

Currently, I am working on a project to create a Skate Dice program that will select random numbers and display the results simultaneously. Unfortunately, I have encountered an issue where the randomly generated number is not being shown; instead, it dis ...

Export a specifically designed object from a module using Python

When working with node.js in JavaScript, you can set module.exports = 13; in a file called module.js, and then import it elsewhere using x = require("module.js");. This will directly assign the value of 13 to variable x. This method is useful when a modul ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Ways to dynamically generate a card using NuxtJS

I'm just starting out with NuxtJS and I'm curious about how to generate a v-card within a v-dialog box. Imagine this scenario: I have an "add" button that triggers a v-dialog, where I can input information into a form. After submitting the form, ...

Creating a sorting function in VueJS requires a few key steps

I'm working on implementing a sorting function in my VueJS code that includes the following options: Price: Low to High, Price: High to Low. Here is my template: <div name="divSortBy"> <span> Sort by: & ...

Creating a drop-down menu within an HTML table along with a D3 bar chart

How can I implement a drop-down menu allowing the user to choose a time interval for this HTML table and d3 bar chart? The time intervals needed are: Now, 24 hours, 48 hours, 72 hours, 1 week, and 1 month. I am relatively new to creating dynamic tables and ...

Tips for looping through each cell in a column of a DataTable to verify its content

I have a table generated using the jquery DataTables API. One of the columns displays word frequencies for each word in the table. If a frequency is less than 40, I want to change that cell to display "unranked" instead of the actual number. How can I ite ...

Is there a way to enable data-add-back-btn using jQuery script?

Currently, I am utilizing jQuery 1.9.1 and jQuery Mobile 1.3.1 to define multiple pages within my project setup: <div id="q1" data-role="page" data-add-back-btn="false" data-back-btn-text="Home"> <div data-role="header" data-position="fixed" ...

Dispatch in React Redux is not intercepted

I've been grappling with this issue for hours and still can't seem to find a solution. When I click the button, the function "getLocation" is being triggered (Confirmed it) However, the dispatch is not getting passed to the reducer. After r ...

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...