What is the best way to access a variable in one file and then utilize it in multiple other files?

My question may seem straightforward, but I'm having trouble finding the right solution.

Within my index.html file, I have the following content:

<html>
<head>
<script src="scalar.js"></script>
</head>
<body>
</body>
<script>
function myFunction() {
  for (i = 0; i < data.length; i++) {
    data[i] *= 5
  }
alert(data)
}
</script>
</head>

In the same directory, there's a file named scalar.js with the line:

var data = [10, 20, 30, 40];

The issue I'm facing is that the array defined in scalar.js is not being utilized in index.html. I've tried including

<script src="scalar.js"></script>
within the body of the HTML file, but it doesn't work.

I would greatly appreciate any assistance! (I prefer to keep the data variable defined in scalar.js rather than setting it in the index file).

UPDATE: Take a look at the code on https://github.com/amosallaei19/NEURepo

Answer №1

Within the <script> block, you are making a reference to the data property within the window global object (since there is no data variable defined in your function).

It's important to note that the let statement does not generate properties on the window object; the declared data variable can only be accessed within the scalar.js file. Properties on the window object are only created using var.

To resolve this issue, adjust the line from:

let data = [10, 20, 30, 40];

to:

var data = [10, 20, 30, 40];

Answer №2

After implementing your code and creating a new file which I included in my index.html, everything seems to be working fine for me. However, I did make some slight modifications to your original code.

<html>
<head>
<script src="scalar.js"></script>
</head>
<body>
</body>
<script>
//let data = [10, 20, 30, 40];
myFunction();
function myFunction() {
  for (i = 0; i < data.length; i++) {
    data[i] *= 5;
    console.log(data);
  }
}
</script>
</html>

The output displayed is as follows:

test.html:13 (4) [50, 20, 30, 40]
test.html:13 (4) [50, 100, 30, 40]
test.html:13 (4) [50, 100, 150, 40]
test.html:13 (4) [50, 100, 150, 200]

Answer №3

When working with scalar.js, one way to store data is by adding it to the window object. This allows you to easily access the data from within your HTML code.

window.numbers = [50, 60, 70, 80]

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

.js script not being rendered within the ng-view

I am facing an issue with my index.html file which contains ng-view. I have included the necessary .js files in the index.html, but these scripts are not being applied to the injected view. index.html <!DOCTYPE html> <html class="no-js css-menub ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...

In Vue 3, what causes the dynamic class value to change along with the ref value when using a function with the ref property for binding?

I'm currently working on Vue code that looks like this. <template> <h1 :class="{ disabled: checkClass() }">Hello</h1> </template> <script setup lang="ts"> import { ref } from "vue"; const ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

Is it possible for two node scripts running on the same machine to interfere with each other's execution

In the scenario where a parent node file (such as an express server) spawns child nodes that execute computationally intense tasks, will these children cause blocking for the parent process? ...

Can 2D canvas elements make use of CSS shaders?

Can CSS shaders, like "fragment" shaders, be utilized in 2D canvas contexts as well? ...

Explore the XML format within a JavaScript string

Currently, I am retrieving a string from PHP using AJAX. This string contains data from a database formatted in XML tags. Upon receiving this string in JavaScript, my objective is to display it as an XML document on the web browser to verify its proper fo ...

Leverage MongoDB output within a JavaScript script

I'm currently facing an issue with passing MongoDB query results to a Javascript file within my view. I'm utilizing handlebars as my view engine and here is a glimpse of my MongoDB schema: var mongoose = require('mongoose'); var Schema ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

Percy snap shot test cannot be executed in Testcafe due to the error message: npm ERR! The script 'test:percy' is

For my initial test with percy snapshot, I used the command below: npm run test:percy Unfortunately, an error message appeared when running the command: xxx.xxx@LPG002572 TC-Visual % npm run test:percy npm ERR! missing script: test:percy npm ERR! A com ...

Exploring the intricacies of Implementing Chromecast Networks, with a curious nod towards potentially mirroring it with

In my current project, I am aiming to replicate the functionality of a Chromecast on a Roku device. To achieve this, I need to first discover the Roku using UDP and then send an HTTP POST request to control it. During a recent developer fest where I learn ...

Learn how to toggle the display of a div using jQuery, just like the functionality on the popular website

Visit Mashable here Below is the script I am currently using: $(document).ready(function(){ $(".show_hide5").mouseover(function(){ $('.selected').removeClass('selected'); $(this).next().fadeIn("slow").addClass(&apo ...

Trimming text from the start and inserting ellipsis in a multi-line passage

My goal is to present a paragraph on the webpage that will be dynamically updated based on user actions. I want to restrict the content to a specified number of lines and if the user tries to exceed this limit, the beginning of the paragraph should be trun ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

The styling of Material UI (MUI) buttons is not displaying correctly

Why are my MUI button components displaying differently than the documentation? I have not made any external .css file or theme changes except for the ones listed. I have also installed the Roboto font and configured the typography. I want any changes I ma ...

adding labels to d3 elements without nesting

I need help creating HTML with tooltips and tooltip text for each <p> tag. While I know this can be achieved using d3, I am currently using a CSS approach because it feels more familiar to me. In an ideal scenario, the desired HTML output should res ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...