JavaScript - Problem transferring an object between two different JavaScript files

Welcome!

I am just starting to learn JavaScript. Excuse me if I don't know all the technical terms yet.

Scenario

Currently, my project consists of three main files:

  • index.html
  • main.js
  • sites.js

index.html

<body>
    <h1>JavaScript Playground</h1>
    <script src="/main.js" type="module"></script>
  </body>

main.js

import { sitesMod } from "/sites.js";
  sitesMod();
  
  console.log(sites);
  

sites.js

function sitesMod() {
    var sites = [
      'https://site1.org/',
      'https://site2.org/',
      'site3.org/'
    ];
  }
  export { sitesMod };
  

Code Explanation

index.html is responsible for running the main.js script.

main.js imports and executes the sitesMod() function from sites.js.

Issue

The expected output of console.log(sites); should be

https://site1.org/, https://site2.org/, site3.org/
.

However, instead of the desired result, console.log(sites); displays sites is not defined.

Current Understanding

I understand that I might need to declare something like var sites = X in main.js, but I'm unsure how to transfer the data stored in var sites in sites.js to var sites in main.js.

Although utilizing the import/export modules seem promising, I'm struggling with the final step of transferring the variable content between files.

I hope this explanation sheds light on my issue. Please feel free to ask for further clarification. Thank you.

Answer №1

Hey there, I've noticed a couple of mistakes in your code:

  1. When you import and link your files in your .js and .html files, you're pointing to the system root folder (e.g., type="/main.js",
    import { sitesMod } from "/sites.js"; 
    ). Instead, use ./main.js or just remove the slash for the actual folder location;
  2. Variables declared inside a function have local scope and are deleted at the end of execution, so you can't access them outside of that scope.
import { sitesMod } from "/sites.js";
sitesMod();

console.log(sites);

This is incorrect. Here are two correct ways to do it:

  1. In your sites.js:
function sitesMod() {
  var sites = [
    'https://site1.org/',
    'https://site2.org/',
    'site3.org/'
  ];

  return sites;
}

In main.js:

import { sitesMod } from "./sites.js";

console.log(sitesMod());
  1. You can also include a console.log() directly inside the function — the first option is preferable ;)
function sitesMod() {
  var sites = [
    'https://site1.org/',
    'https://site2.org/',
    'site3.org/'
  ];

  console.log(sites);
}

export { sitesMod };

Tip: Learn more about variable scope and the differences between var, let, and const. Also, read up on Linux to understand the difference between / and ./.

I hope this helps you with your studies! XD

Excuse any mistakes in my English...

Answer №2

There are a couple of issues that need to be addressed here. The function sitesMod currently does not have a return value, which means that when it is called in main.js, nothing will happen. To fix this, update the function as follows:

function sitesMod() {
  var sites = [
    'https://site1.org/',
    'https://site2.org/',
    'site3.org/'
  ];
  return sites;
}

The second issue lies in how the function is being used. Simply calling the function does not declare the variable sites outside of the function's body. To access the sites variable, you can make use of the following code snippet:

import { sitesMod } from "/sites.js";

console.log(sitesMod());

Please note that I have not tested the code.

Answer №3

function sitesMod() does not return any value when executed, and it does not create a global variable named sites

An alternative approach would be:

sites.js

function sitesMod() {
  var sites = [
    'https://site1.org/',
    'https://site2.org/',
    'site3.org/'
  ];
  return sites;
}

main.js

import { sitesMod } from "/sites.js";
const sites = sitesMod();

console.log(sites);

However, considering the simplicity of sites.js, it would be more straightforward to streamline the code like this:

sites.js

const sites = [
  'https://site1.org/',
  'https://site2.org/',
  'site3.org/'
];

export { sites };

main.js

import { sites } from "/sites.js";
console.log(sites);

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

Tips for directing attention to a specific row with an input field in JavaScript

I duplicated a table and added an input field for users to search or focus on a specific row. However, there are two issues: When a user enters a row number, the table displays the wrong row - for example, if the user enters 15, the table shows row number ...

When two divs are activated, the third div goes into invisible mode

I attempted this code, but it doesn't appear to be functioning correctly. if(div1)&& (div2)==display:none { div3=display:none; } else { div3=display:block; } ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

How can the camera in ThreeJS be shifted horizontally without being affected by its current orientation?

In my ThreeJS setup, the camera is able to move through a 3D world and change its lookAt multiple times while in motion. As a result, camera.getWorldDirection() will always be more or less random. Now, I require the camera to move specifically left, right ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Ensure that the authorization header is properly set for all future client requests

I need help figuring out how to automatically set the "Authorization: Bearer ..." header for user requests. For example, I save the user to the database, generate a token, and send a welcome email with the token : await user.save() const token = await use ...

Issue with jQuery datepicker not triggering onChangeMonthYear event

Recently, I've been working on creating an app using jQuery date picker. To see my progress so far, feel free to check out this fiddle: http://jsfiddle.net/Lf6sD/2/. In the options, there's a mention of an onChangeMonthYear event that should trig ...

Using React Native to take user input and store it in an array in

As a newcomer to react-native and javascript, I am unsure where to begin with this small project. Participants are allowed to pick one option for each question. Which type of pet do you prefer? a dog a cat What color would you like your pet to be? ...

Is it possible to nest v-for directives within a component file?

Even after going through the VueJS tutorials multiple times, I am still unable to find a solution to this problem. My issue revolves around displaying a list of lists using accordions, which is supposed to work smoothly with vue-strap components. For exa ...

Exploring AngularJS: The Innovative Navigation Bar

My goal is to incorporate the functionality demonstrated in this example: https://material.angularjs.org/1.1.1/demo/navBar To achieve this, I have created the following index.html: <!DOCTYPE html> <html lang="en"> <head> &l ...

Update the select tag to display as radio buttons

Hey there, I've got a webpage where users can rate different systems. I've written a JavaScript function to dynamically add and remove systems for evaluation. The only issue is that I have to manually change the radio button names to prevent th ...

Issue with Vue.js - Double curly braces not rendering data on the page

I've recently delved into the world of vue.js Strangely enough, the double curly braces syntax doesn't seem to be rendering for me. However, when I utilize the v-text directive, everything falls into place. Here's a snippet of my code: HTM ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

What are the steps to develop an ElectronJS application that displays "Hello world!" in the console after a button click?

Can anyone offer a helping hand? From the depths of imagination to the realms never before conceived by humans. Check out this HTML snippet: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hell ...

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

Implementing personalized callback methods for AJAX requests in Prototype

After refactoring my code to use proper objects, I am facing an issue with getting Prototype's AJAX.Request to work correctly. The code snippet below is functioning within the context of YUI's DataTable: SearchTable.prototype.setTableColumns = f ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Refreshing Page Following Ajax Submission

Currently, I am working on a Single Page Application using asp.net MVC. When I make a post request to the server using Ajax, the Web API performs parameter validation and then returns a Json String. The code snippet for the Web API function is shown below ...