0

I have seen, google places api docs, suggesting use of global variables outside of the functions, like:

var placeSearch, pauto, geocoder;

I want to use data returned from $.get, outside of the function.
Could I also use a global variable that will be fed by data inside a callback function?

var glo_var;
function callback(data){
         glo_var = data;
}

function codeAddress(address) {
    geocoder.geocode({ 'address': address}, 
    function(response, status) {
     if (status == 'OK')
      {
       var senddata = $.get('/myurl',{params}, function (data){ callback(data) });
      } else {
       }
  });
}

Any other way, that I could make use of returned datafrom $.get. I do not understand closures.

EDIT - Why is this a duplicate, I am asking where to store the returned data, I already know how to get it? It's the use of globals that i am not sure of, but since google api uses it, i asked about it here.

ksalf
  • 37
  • 8
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Mar 30 '19 at 17:26
  • **Aside note:** Change to: `$.get('/myurl',{params}, callback);` – Ele Mar 30 '19 at 17:27
  • 1
    It depends. You're obviously using jQuery so `$` would be a global variable too - would that not be OK in your eyes? Certain things just make sense to attach to the window scope when used, while other things might as well hide in an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE). Your example here does _not_ make sense to put in the global scope, so simply wrap it in a function expression as I linked. – h2ooooooo Mar 30 '19 at 17:49
  • @h2ooooooo : I have seen many a times things attached to window scope, but I never understood it. Should I use IIFE for global variables? – ksalf Mar 30 '19 at 17:53
  • @Ele: Thank you sir, I'll be using that only from next time. – ksalf Mar 30 '19 at 17:54
  • @h2ooooooo: OK sir, your last line was not there, when I asked you about IIFE, thanks again. – ksalf Mar 30 '19 at 17:55
  • You're questing in the title does not seem to match the question you want an answer to. In one locations you ask about closures, and in another you ask about global variables. Please limit your questing to a single, specific issue, so we Can efficiently and clearly answer. – SherylHohman Mar 30 '19 at 18:01
  • 1
    Possible duplicate of [Global variables in JS harmfull?](https://stackoverflow.com/questions/19313248/global-variables-in-js-harmfull) – SherylHohman Mar 30 '19 at 18:03
  • 1
    @SherylHohman: Thank you so much for that link, Sir, that exactly is what I am looking for ! – ksalf Mar 30 '19 at 18:05
  • @h2ooooooo: Sir, I did exactly as you linked. However, nothing is happening, it's just blank, no error. After wrapping it like `(function() { ... google places autocomplete code ... })();`, do I need to return something, or send something into it, like the text captured from the search-input-box? – ksalf Mar 30 '19 at 20:18
  • @ksalf That _should_ execute the function. What does your JS console tell you? Does it give you an error? `console.log('test');` is always useful to put in places, to see if the code gets there (unless you want to go more advanced and use breakpoints.. if so look up " js breakpoints" on google). Anything that you're planning to do with the `glo_var` variable should be done _inside_ of your `callback` function. – h2ooooooo Mar 30 '19 at 20:19
  • @h2ooooooo :Thank you for replying, Sir.Console shows 3 `get` request to google api services. But autocomplete drop down list is not there below the input box. When I use it without iife it works as expected. – ksalf Mar 30 '19 at 20:21
  • @h2ooooooo - `AutocompletionService.GetPridictions?` isn't getting called, although the code is exactly the same. – ksalf Mar 30 '19 at 20:26
  • And you're not getting any error in the console (not your network tab, but the console tab)? Do you see the `console.log` statements that you put in there, to make sure it gets called? What does your actual code look like since I can't see that method anywhere? – h2ooooooo Mar 30 '19 at 20:29
  • @h2ooooooo: No Sir, no error in console tab. Authentication is getting called for js link of google api. It seems as if the code is not getting called at all. And, I am not even using callback this time as I was just trying to test iife. Should I post my code here, by editing the question? – ksalf Mar 30 '19 at 20:34
  • @h2ooooooo : Sir, I have asked a new question with entire code there, please have a look when you are free https://stackoverflow.com/questions/55435642/iife-how-to-put-google-places-api-working-code-under-iife – ksalf Mar 30 '19 at 21:07

3 Answers3

2

You can just wrap everything inside self invoked function (it's closures but it's simple)

(function(){...})() means function will call itself, that's all.

Best practice is when you wrap every .js file inside this self invoked function so it's not global.

Your code:

(function(){
var glo_var;

function callback(data){
         glo_var = data;
}

function codeAddress(address) {
    geocoder.geocode({ 'address': address}, 
    function(response, status) {
     if (status == 'OK')
      {
       var senddata = $.get('/myurl',{params}, function (data){ callback(data) });
      } else {
       }
  });
}
})();
  • Thank you sir ! Just 1 question, is glo_var not a global if I use it the way you have explained? – ksalf Mar 30 '19 at 17:58
2

so the reason for to avoid using global variables as much as possible as stated in the previous answers. It is about easily overriding problem and troubleshooting when some global values are being overriden. From my own experience, I usually create an utility to handle sharing values. The idea is as following

//global.js
(function(){
  const context = {};
  function setGlobalValue(key, value) {
    context[key] = value;
  }
  function getGlobalValue(key) {
    return context[key];
  }
  window.setGlobalValue = setGlobalValue;
  window.getGlobalValue = getGlobalValue;
}());
// app.js
function codeAddress(address) {
  geocoder.geocode({ 'address': address}, 
  function(response, status) {
   if (status == 'OK')
    {
     var senddata = $.get('/myurl',{params}, function (data){     setGlobalValue('codeAddress', data) });
    } else {
     }
});
}
// get value here
console.log(getGlobalValue('codeAddress'));

by this way we can track all the global values by searching for setGlobalValue since this is the only way to set "global" value context.

duc mai
  • 1,412
  • 2
  • 10
  • 17
1

Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global variables are not bad and not even a security concern, but it shouldn’t overwrite the values of another variable.

On the usage of more global variables in our code, it may lead to a maintenance issue. Let’s say we added a variable with the same name. In that case, get ready for some serious bugs.

To avoid the usage of global variables, use the local variables and wrap your code in closures. You can also avoid this by wrapping the variables with json:

var wrapperDemo= {
   x:5,
   y:function(myObj){
   }
};

Above, if you want to call x, then call it using:

wrapperDemo.x

Which would return 5 for you...

Bilaal Rashid
  • 828
  • 2
  • 13
  • 21
MonneratRJ
  • 124
  • 10
  • Thanks for replying sir ! If I use 3 functions under `wrapperDemo`, could I call `function1()` like- `wrapperDemo.function1()` whenever and wherever i like? – ksalf Mar 30 '19 at 17:49
  • Yup, if that's a function, if it's an attribute, then you can leave the () out... – MonneratRJ Mar 31 '19 at 18:09