Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Is there any way to export a variable and change it after importing it?

I'm using Webpack, and I have a function.js file with this code:

import { randomNum } from '../index.js';

export function getSlidePrev() {
  if (randomNum > 1) {
    randomNum -= 1;
    setBg(randomNum);
  }
}

And in my main.js file I have this:

function getRandomNum(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
export let randomNum = getRandomNum(firstSlideNumber, lastSlideNumber);

const slidePrev = document.querySelector('.slide-prev');
slidePrev.addEventListener('click', getSlidePrev);

I get this type of error:

Uncaught TypeError: Cannot set property randomNum of #<Object> which has only a getter
    at HTMLButtonElement.getSlidePrev 

I tried to google, but I couldn't solve this issue. Someone says it's because of using Babel.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

An imported variable is a read-only, you cannot modify it in the file where it's imported. Here is what mdn says about it:

The static import declaration is used to import read-only live bindings which are exported by another module. The imported bindings are called live bindings because they are updated by the module that exported the binding, but cannot be modified by the importing module.

You can turn randomNum into an object if you want to mutate it across different imports. For that change it in index.js to:

export const randomNum = {value : 1000};

And use it this way:

import { randomNum } from "../index.js";

export function getSlidePrev() {
  if (randomNum.value > 1) {
    randomNum.value -= 1;
    setBg(randomNum.value);
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!