# Best way to retrieve parameters from associative array in javascript?

Within a function, I want to grab a set of parameters from a named array. What is the most efficient way of testing if the parameter exists in the array, and if it does, use it as a variable? I came up with a few alternatives.

target = $('#page_links') if ( functionobject.target ) { target = functionobject.target } //method 2: var target = '' if ( functionobject.target ) { target = functionobject.target } else { target = final_array } //method 3: target = functionobject.target if (typeof target == 'undefined') { target =$('#page_links')
}

• I think the terminology in your question might be bad. Instead of "parameters from a named array", you probably mean "attributes in an object". Arrays are supposed to sequences of elements, indexed by numeric subscripts. Objects have named attributes. Arrays happen to be objects in JavaScript, but it's bad style to use arrays when just an object will suffice. – 200_success Oct 3 '13 at 8:36
• Thanks, I was aware that these "associative arrays" simply are objects, but since the term "associative arrays" and "named arrays" seem to be frequently used, I thought that it could be helpful somehow. Thanks for clarifying. I used the term "parameters" since the point of my task is to the variables we are collecting as parameters in a function, but that is not really relevant for my question, so right you are. :) – Skarven Oct 3 '13 at 9:06

var target = functionobject.target || $('#page_links');  How did I arrive at that? The important point to get across is that no matter what happens, you want to assign something to target. One first attempt to express that would be to use the ternary operator var target = functionobject.target ? functionobject.target :$('#page_links');

However, the repetition of functionobject.target is ugly. It would be better to use the short-circuit evaluation feature of the a || b operator. If a is true, then evaluation stops, and the value of the expression is just a. Otherwise, the value of the expression is b.