Sandesh Kandel
Sandesh Kandel

Reputation: 15

how to access object from one js file to another?

 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?

Upvotes: 0

Views: 264

Answers (3)

fingerprints
fingerprints

Reputation: 2960

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();

Upvotes: 0

RodCardenas
RodCardenas

Reputation: 604

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.

Upvotes: 0

kidwon
kidwon

Reputation: 4524

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
 }

Upvotes: 1

Related Questions