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\$
2
  • \$\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\$ Oct 3, 2013 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, 2013 at 9:06

1 Answer 1

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\$
2
  • \$\begingroup\$ Excellent, that worked perfectly. Thanks for the one-liner! \$\endgroup\$
    – Skarven
    Oct 3, 2013 at 9:08
  • \$\begingroup\$ If that worked for you, then would you please mark this as your accepted answer? Thanks. \$\endgroup\$ Oct 4, 2013 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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