0

I understand that an array is being declared in line 3.

Line 6 queries the array. But how? I don't see any variable being passed around.

$(function(){

    var currencies = ["stack", "over", "flow"];

    // setup autocomplete function pulling from currencies[] array
    $('#autocomplete').autocomplete({
        lookup: currencies,
        onSelect: function (suggestion) {
        $('#outputcontent').html(thehtml);
        }
    });

});

Autocomplete Search: https://codepen.io/DinhTrieu/pen/PwXqGR/

Mac Duff
  • 3
  • 1
  • Re the [*"What is the scope of variables in JavaScript?"*](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) dupetarget, I'm not immediately seeing what scope really has to do with this. It's not like `currencies` is used in a closure or something... – T.J. Crowder Jul 20 '18 at 14:15
  • @T.J.Crowder I think the question is "Why is the `currencies` variable available within the the following function". The answer being; they are declared within the same scope. Maybe I am misunderstanding the question? – Turnip Jul 20 '18 at 14:17
  • @Turnip - It's not used in a function. It's used in a function *call*, but that's not unusual... – T.J. Crowder Jul 20 '18 at 14:18
  • Reopen if you like. I'm still not convinced that the other question doesn't answer this question personally. – Turnip Jul 20 '18 at 14:20
  • @Turnip - I'll leave it as-is, it's probably not a significant question anyway. :-) – T.J. Crowder Jul 20 '18 at 14:25

1 Answers1

1

The {...} structure being passed into autocomplete is an object initializer; it creates an object with the listed properties in it. One of those properties is lookup: currencies, which passes the array into the function as the lookup property of the object. So autocomplete has access to the array, because it has access to the object with the lookup property on it.

Here's a simpler example:

var currencies = ["stack", "over", "flow"];
var options = {
  lookup: currencies
};
console.log("options.lookup[0] = " + options.lookup[0]);
foo(options);

function foo(opts) {
  console.log("in foo opts.lookup[0] = " + opts.lookup[0]);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • That made sense. Anyway to store the query in a variable? – Mac Duff Jul 20 '18 at 14:40
  • @MacDuff - It's not a query, it's just an array, and it's stored in (well, a reference to it is stored in) `currencies`. I suspect `autocomplete` also lets you specify a function that gets called instead, so you can fine-tune what you present. (If it's the one from jQuery UI, I know it does.) – T.J. Crowder Jul 20 '18 at 15:03