0

I want to use the same variable in 2 javascript files modify it in both files and get the updated value to both files. I tried this. But it doesn't worked.

first.js

let marks = 0;

function func1() {
    function add() {
        marks = marks + 5;
        alert(marks);
        window.location.replace("second.html");
    }
    return {
        add:add;
    }
}

export default func1;

second.js

import func1 from '../first';
func1().add();

function func2() {
    function add2() {
        marks = marks + 5;
        alert(marks);
        window.location.replace("third.html");
    }
    return {
        add2:add2;
    }
}

export default func2;
Vidu
  • 33
  • 1
  • 7
  • It's not a good idea to have a global variable and change it. Could you please explain what you are trying to achieve? Knowing more about the context we could provide a good answer. – Esdras Xavier Dec 13 '21 at 12:09
  • I want to add 5 marks from the first page if I choose the correct answer. And then redirect to the second question page. If the player choose the correct answer, marks will increase by 5. – Vidu Dec 13 '21 at 12:13
  • So, as I understand each page is a question, rigth? In this case what you are trying to do will not work, basically each time you redirect to a new page you JS will be reloaded, that means that your variable will be reinitialized every time. The best option would be having a single page, and you should show each question in this page. – Esdras Xavier Dec 13 '21 at 12:19
  • You can also change `marks = marks + 5` to `marks += 5` – RedYetiDev Dec 13 '21 at 12:29
  • If you are going to new pages, a new process is loaded and your in-memory variables are gone. See https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads – Ruan Mendes Dec 13 '21 at 12:32
  • Store `marks` in localStorage. You can access it on every page, and update it on every page. Warning: you may have to check that it exists on each page before you go about using it or updating it. [MDN LocalStorage Docs](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) – TJBlackman Dec 13 '21 at 12:46
  • Or write a cookie with the current mark value and read it at the next page. – Michel Dec 13 '21 at 13:41
  • Thank you very much everyone – Vidu Dec 13 '21 at 17:57

0 Answers0