0
var products=[1,2,3];
product_edits();//GIVES [1,2,3].

myApp.onPageInit("mypage",function(page){
    console.log(products);//undefined
    var products=[3,2,1];
    product_edits();//GIVES [1,2,3]?? Shouldn't this be 3,2,1?
});

function product_edits(){
    $(element).click(function(){
        console.log(products);
    });
}

I'm certain pageInit was called. but i don't know why products still gives 1,2,3 when i thought the values should have changed to 3,2,1.

Lawrence
  • 717
  • 1
  • 12
  • 25

1 Answers1

0

This is because you are re-declaring products in a local scope of onPageInit. If you re-declare it in the local scope of onPageInit, it will not be available outside the function.

Try reassigning the product variable instead of re-declaring in local scope.

Or even better pass the products array as a function argument if you don't want to reassign the global variable.

product_edits(products);
rishipuri
  • 1,498
  • 11
  • 18
  • but products on the global scope is not retrievable as well. This means the page is reloaded isn't it? – Lawrence Mar 23 '17 at 10:12
  • also i recalled products_edits inside of pageInit, shouldn't product_edits take the variable from the calling function? – Lawrence Mar 23 '17 at 10:14
  • You can retrieve the products variable declared in the global scope from the window object. So window.products should give you the global variable. – rishipuri Mar 23 '17 at 10:16
  • If you want to understand how variable scope works in javascript, take a look at this answer: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – rishipuri Mar 23 '17 at 10:21
  • Thank you. The window object solved my problem. I redeclared only because i wasn't able to make amendments to the global variable. – Lawrence Mar 23 '17 at 10:31