JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner:

// module1.js

let directory;
export { directory };

Now, I am trying to access it in a separate module like so:

// module2.js

import { directory } from '../js/module1.js';
directory = gui.createFolder( 'User Data' );

Error: Cannot assign to a constant variable.

Answer №1

Imports serve as read-only connections to the original variable located in the exporting module. The term "read-only" signifies that direct modifications are not possible. On the other hand, the term "live" indicates that any alterations made by the exporting module can be observed.

In cases where a module needs to permit other modules to adjust the values of its exports (which is typically infrequent), it must export a function intended for that purpose. For example:

alpha.js:

export let folder;
export function setFolder(f) {
    folder = f;
}

beta.js:

import { folder, setFolder } from "./alpha.js";

console.log(folder); // The output will be `undefined` unless altered by another module
setFolder(gui.addFolder("Avatar Measurements"));
console.log(folder); // The output will reflect whatever `gui.addFolder` returns

However, it remains highly unusual for a module to allow external modifications to its exports in this manner.


As requested, here is an instance of exporting an object instead:

alpha.js:

export let shapes = {};

beta.js:

import { shapes } from "./alpha.js";

shapes.folder = gui.addFolder("Avatar Measurements");

It is not immediately evident why this object must reside in alpha rather than being local in beta.

Answer №2

The issue arises because when you import folder from ../js/first.js, you are creating a constant named folder. Constants cannot be reassigned, so avoid using == or === as they are comparison operators and won't alter the value of folder.

To transfer data from second.js to first.js, consider exporting a function from second.js. If you opt not to do this, then choose a different variable name, such as folder_ (and make sure to declare it initially with var folder_;).

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

Numerous Customized Google Maps

On my contact page , I have a Google Map V3 that is styled and mostly functional, except for some sprite image display issues. Now, I need to include the same JSON data in two separate maps on my showrooms page . How can I style multiple maps with differen ...

JavaScript Delayed Redirection

I'm attempting to launch opera from the command line and have it redirect to a page after 30 seconds. Here's what I currently have: C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='htt ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

When the user clicks, position a div directly below another div

Can anyone help me figure out how to center a div underneath another one when a specific div is clicked using programming? I've tried multiple solutions but nothing seems to work. Below is the code snippet that I have written. You can also check out t ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

Displaying variables as HTML in Node.js involves rendering the variable data

Currently experimenting with displaying a Node.js variable as HTML. This is my setup in app.js using Express: Package.json "dependencies": { "body-parser": "~1.12.0", "cookie-parser": "~1.3.4", "debug": "~2.1.1", "express": "~4.12.2", ...

Using jQuery to change date format from mm/dd/yy to yyyy-dd-mm

I need to transform a date in mm/dd/yy format from an ajax response into yyyy-mm-dd format using jquery. Is there a built-in function in jquery that can handle this conversion for me? ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

What is the Best Way to Toggle the Visibility of Specific Buttons in a Table Using Jquery?

<html> <head> <script> $( "#clickMeButton" ).click(function() { $(this).next("#hiddenButton").slideToggle( "slow", function() { // Animation complete. }); }); </script> </head> <body> <table> <tr& ...

Additional unnecessary event listeners (deleteComponent) were provided to the component but could not be inherited automatically

Dear community, I am facing an issue with emitting events from my child component to the parent. Strangely, all other components work perfectly fine with the same code except for this particular one. Let me provide you with the relevant code snippets: Ch ...

Gulp-sourcemaps now exclusively provides the source JavaScript file

Whenever I try to use sourcemaps, I only get the source value returned no matter what. Broswerify.js // if custom browserify options are needed var customOptions = { entries: ['./frontend/js/app.js'], debug: true }; var finalOpts = assi ...

What is the best way to determine the total number of classes that come before a specific element

Currently, this is my approach: <script> function Answered(str) { var script = document.getElementsByClassName('Answered')[str]; if(script!==null) {script.setAttribute("style", "");} } </script> <span class=Answered style=" ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

What could be causing checked="checked" to fail validation in JavaScript?

I'm feeling a bit puzzled about this issue. Here's the HTML code I have - <input type="radio" id="20577091" name="q_engine" value="20577091" style="position: absolute; opacity:0;" checked="checked" /> and here is the corresponding JavaScr ...

Using jQuery to access the ID of a div and create a custom close button

I am trying to implement a close button for my popup DIVs. Each one has a unique ID and I want to hide them by setting the CSS 'display' property to 'none' when closed. However, the following example is not functioning as expected. I a ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Analyzing the differences in environment management between express and dotenv

Lately, I've noticed an abundance of tutorials and articles discussing NodeJS and the dotenv library. One common practice that keeps coming up is defining an ENV_MODE=development variable within the config.env file. However, it got me thinking - does ...

Using Vue.js to invoke an external JavaScript function for search functionality

In my vue.js application, I have a list of users with backend pagination. Now I want to implement a search functionality. I attempted to call the method like this: watch: { search: function() { Crud.methods.getItems(); } }, Howe ...

Having trouble capturing the 'notificationclick' event in the service worker when using Firebase messaging with Nuxt.js and Vue.js?

Experiencing difficulties in detecting events other than install, activate, or push in my firebase-messaging-sw.js. Notifications are being received and displayed, but I am unable to detect the event handler for notificationclick. When a firebase notificat ...

Trying to modify the chosen option while filtering an ajax source using select2?

I am currently integrating the select2 library within a Bootstrap 4 modal in the following manner: <div class="form-group" id="fg-jbInd"> <label for="jbIndustry" class="control-label"gt;Industry * <sele ...