1
\$\begingroup\$

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')
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – 200_success Oct 3 '13 at 8:36
  • \$\begingroup\$ 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. :) \$\endgroup\$ – Skarven Oct 3 '13 at 9:06
4
\$\begingroup\$

I would say

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.

\$\endgroup\$
  • \$\begingroup\$ Excellent, that worked perfectly. Thanks for the one-liner! \$\endgroup\$ – Skarven Oct 3 '13 at 9:08
  • \$\begingroup\$ If that worked for you, then would you please mark this as your accepted answer? Thanks. \$\endgroup\$ – 200_success Oct 4 '13 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.