0
document.getElementById('button').addEventListener('click', function() {
ApiCall()
console.log(lol)

});



function ApiCall() {
var lol = "this is a test";
}

I have looked into the javascript scopes but how would i pass this variable to the first function ?

Kevin G
  • 2,325
  • 3
  • 16
  • 30
  • 1
    use global var? or save your data as one data attribute of one element? – Sphinx Mar 14 '18 at 00:31
  • 3
    [`return lol;`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) – Related: [What is lexical scope?](https://stackoverflow.com/questions/1047454/what-is-lexical-scope) – Jonathan Lonowski Mar 14 '18 at 00:33
  • Where would you put the return lol ? i tried putting it under the Apicall() but it doesn't seem to work thank you for the link will sure read up on this – Kevin G Mar 14 '18 at 00:40

1 Answers1

2

You should return the value from your function. Like this:

document.getElementById('button').addEventListener('click', function() {
  var passed_lol = ApiCall()
  console.log(passed_lol)
});

function ApiCall() {
  var lol = "this is a test"
  return lol;
}
<input id="button" type="button" onclick=stop() value="clickme">
Mark
  • 90,562
  • 7
  • 108
  • 148
  • Works like a champ, but if i had to pass 4 variables would the Apicall run for each variable ? because the Apicall is making requests – Kevin G Mar 14 '18 at 00:52
  • I guess that depends on what you mean. Do you need to call the API four times? Or does a single call to the API return four values. Either way, the function can just return an array or object, which can include as many values as you like. – Mark Mar 14 '18 at 00:55
  • Also... if it is an API call to a remote service (XHR aka AJAX, etc), it is likely to be asynchronous, so things might need to be a little more complex, requiring the use of things like [`Promise`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and/or [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function); or the more traditional, callback function. – Useless Code Mar 14 '18 at 06:58