1

Learning about functions and can't understand why they break when I try to make a key a parameter. They work fine when making a value a parameter but not the key. What don't I know about JavaScript or jQuery that is breaking this?

example:

function box(e, a, q, r) {
    $('div').animate({
        r : e,
        'height' : a
    }, q);
}

box('200px', '200px', 500, 'width');

if I remove the 4th parameter r, it works fine. but something about making a key in a key/value pair doesn't work. Teach me, internet.

wetjosh
  • 6,288
  • 4
  • 23
  • 32

1 Answers1

5

In object literal all keys are identified as strings. To use variables as keys for JS objects use square bracket notation:

function box(e, a, q, r) {
    var config = {
        height : a
    };
    config[r] = e;

    $("div").animate(config, q);
}

READ MORE: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Should height be enclosed in quotes? I was under the impression that is only required for reserved keywords. – Brad M May 17 '13 at 21:13
  • @BradM It doesn't really matter. – VisioN May 17 '13 at 21:14
  • yeah, I got burned before for not using quotes, so I just use them all the time now. – wetjosh May 17 '13 at 21:16
  • Sometimes you may use a reserved word as a key. Mostly it can make problem in IE, where, for example, `class` is a reserved word. So when you use `{ class : "value" }` IE may raise a syntax error. For such cases you should surround key name in quotes. – VisioN May 17 '13 at 21:18
  • Or avoid using keywords. Prepend them if you like: `{elem_class:"value"}` – rGil May 17 '13 at 21:26
  • @BradM Quotes are also required for invalid identifiers - like a string containing special characters or starting with a number (and not containing non-numbers)...`testing-key` or `1a` – Ian May 17 '13 at 21:32
  • @VisioN hmm. I wish I was smart enough to understand your answer but I am too noob. For now I'll keep wondering why it's so much harder for keys than for values... – wetjosh May 17 '13 at 21:33