0
 function fetchValue(){
   var bill = JSON.parse(localStorage.getItem('bill'));
   var result = document.getElementById('total');


   result.innerHTML='';
    var total=0;
   for(var i=0;i < bill.length;i++){
      var items= bill[i].items;
      var date= bill[i].date;
      var price= bill[i].price;
      total+= parseFloat(price);
 }
 }

In the above code I have value total which is inside function fetchValue() in the JavaScript file named main.js. Can i access total in another JavaScript file calculate.js? how?

  • of course, you can, you have to call this method in `calculate.js` and just add in the function at the end `return total;` – fingerprints Apr 04 '17 at 17:01

3 Answers3

1
window.myValues = {};

function fetchValue(){
   var bill = JSON.parse(localStorage.getItem('bill'));
   var result = document.getElementById('total');


   result.innerHTML='';
   var total=0;
   for(var i=0;i < bill.length;i++){
      var items= bill[i].items;
      var date= bill[i].date;
      var price= bill[i].price;
      total+= parseFloat(price);
   }

   return total;
 }


 window.myValues.total = fetchValue();


 // window.myValues.total is available everywhere with 
 if(window.myValues) {
   // .... window.myValues.total
 }
kidwon
  • 4,448
  • 5
  • 28
  • 45
0

You could return total at the end of fetchValue. Then, within calculate.js you can call fetchValue() after importing main.js. It would be easier to answer your question if you could provide the structure of your code.

//main.js
export function fetchValue(){
 var bill = JSON.parse(localStorage.getItem('bill'));
 var result = document.getElementById('total');
 result.innerHTML='';
 var total=0;

 for(var i=0;i < bill.length;i++){
  var items= bill[i].items;
  var date= bill[i].date;
  var price= bill[i].price;
  total+= parseFloat(price);
 }
 return total;
}

//calculate.js
import { fetchValue } from 'pathTo/main.js';
function someFunction(){
  fetchValue();
}

Take a look at this answer too.

Community
  • 1
  • 1
RodCardenas
  • 585
  • 6
  • 14
0

Of course, you have to add the return sentence in your function, so you have in your main.js file this:

//main.js
function fetchValue(){
    var bill = JSON.parse(localStorage.getItem('bill'));
    var result = document.getElementById('total');


    result.innerHTML='';
    var total = 0;
    var size = bill.length; //it's better have another variable with the lenght value for optimization of calcul

    for(var i=0;i < size; i++){
        var items= bill[i].items;
        var date= bill[i].date;
        var price= bill[i].price;
        total+= parseFloat(price);
    }

    return total; // return your value
}

And in the other file calculate.js you add the call to the function

//calculate.js
var total = fetchValue();
fingerprints
  • 2,751
  • 1
  • 25
  • 45