By speendo

2010-02-16 16:05:24 8 Comments

Why does the following work?

    { 'top' : 10 }, 10

Whereas this doesn't work:

var thetop = 'top';
    { thetop : 10 }, 10

To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.


@kube 2016-03-15 23:17:35

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

var obj = {
  [key]: value

Where key can be any sort of expression (e.g. a variable) returning a value.

So here your code would look like:

  [thetop]: 10
}, 10)

Where thetop will be evaluated before being used as key.

@Dieter Schmitt 2019-04-09 23:42:20

I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.


var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

matrix[a] = {[b]: {[c]: d}};


var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

function addObj(obj, key, value) {
  obj[key] = value;
  return obj;

matrix[a] = addObj({}, b, addObj({}, c, d));

@Ciro Santilli 新疆改造中心996ICU六四事件 2014-06-16 12:35:46

ES5 quote that says it should not work

Note: rules have changed for ES6:


PropertyName :

  • IdentifierName
  • StringLiteral
  • NumericLiteral


The production PropertyName : IdentifierName is evaluated as follows:

  1. Return the String value containing the same sequence of characters as the IdentifierName.

The production PropertyName : StringLiteral is evaluated as follows:

  1. Return the SV [String value] of the StringLiteral.

The production PropertyName : NumericLiteral is evaluated as follows:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. Return ToString(nbr).

This means that:

  • { theTop : 10 } is the exact same as { 'theTop' : 10 }

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.

  • It is not possible to write object initializers (literals) with variable keys.

    The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).

@Ciro Santilli 新疆改造中心996ICU六四事件 2015-07-14 15:32:57

Downvoters: I was the first to quote any standard on this question. The ES6 quote on the top answer was edited after I answered, and that standard was not yet accepted at the time. If you happen to know why else I'm getting downvotes, please explain, I just want to learn. I might as well get the peer pressure badge...

@Bergi 2015-08-02 21:22:12

I guess the downvote was mostly because your answer doesn't offer a solution, and is "not useful" in that regard. Voting towards peer pressure :-)

@Ciro Santilli 新疆改造中心996ICU六四事件 2015-08-03 05:17:26

@Bergi thanks for having the courage! :-) But I think I have answered the question directly: Q: "Why does the following work?". A: because ES5 says so. "What to do about it?" is implicit. Did you downvote the top question for saying "It is impossible" without a standard quote before someone edited in the ES6 solution?

@Bergi 2015-08-03 13:10:48

Ah, right. I typically cite the specific questions in a blockquote to make it clear when I answer them directly. Quoting the standard can make a good answer even better, but currently your post doesn't even answer the question imo. Stating what can make a key in ES5 doesn't imply how they work. Surely thetop is an IdentifierName, so why does it not work? That question is still open.

@Ciro Santilli 新疆改造中心996ICU六四事件 2015-08-03 14:23:02

@Bergi thanks again for explaining to me! I have updated it to make it more explicit. I hadn't done it before because I though it was obvious, because we can write {a:1}.a, so a clearly not expand the variable value in the identifier case. But yes, explaining further is an improvement in this case.

@Ciro Santilli 新疆改造中心996ICU六四事件 2018-03-16 10:53:53

OMG, reading those comments from the past. I should really chill.

@Yury Laykov 2019-02-13 12:19:01

You can do it this way:

var thetop = 'top';
    new function() {this[thetop] = 10;}, 10

@ROROROOROROR 2019-02-13 08:01:12

If you want object key to be same as variable name, there's a short hand in ES 2015. New notations in ECMAScript 2015

var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10

@sh32my 2018-10-09 00:01:04

You could do the following for ES5:

var theTop = 'top'
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10

Or extract to a function:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')

var theTop = 'top'
  newObj(theTop, 10), 10

@darcher 2018-10-02 02:43:13

ES5 implementation to assign keys is below:

var obj = Object.create(null),
    objArgs = (
      (objArgs = {}),
      (objArgs.someKey = {
        value: 'someValue'
      }), objArgs);

Object.defineProperties(obj, objArgs);

I've attached a snippet I used to convert to bare object.

var obj = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': [
  'key4': {
    'key5': 'value5'

var bareObj = function(obj) {

  var objArgs,
    bareObj = Object.create(null);

  Object.entries(obj).forEach(function([key, value]) {

    var objArgs = (
      (objArgs = {}),
      (objArgs[key] = {
        value: value
      }), objArgs);

    Object.defineProperties(bareObj, objArgs);


  return {
    input: obj,
    output: bareObj


if (!Object.entries) {
  Object.entries = function(obj){
    var arr = [];
      arr.push([key, obj[key]]);
    return arr;


@Deepu Reghunath 2018-03-28 10:03:42

This way also you can achieve desired output

var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});
<script src=""></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>

@Andy E 2010-02-16 16:15:53

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10; 

// Pass the resulting object to the animate method
    aniArgs, 10  

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

var thetop = "top",
    obj = { [thetop]: 10 };

console.log(; // -> 10

You can use this new syntax in the latest versions of each mainstream browser.

@speendo 2010-02-16 16:38:49

I understand! Thank you! Shoudln't this also work with eval? I mean it doesn't work in my example at the moment, but I thin it should... :-)

@Andy E 2010-02-16 16:44:11

@Marcel: eval() wouldn't work inside an object literal for dynamic property names, you'd just get an error. Not only that, but eval() really shouldn't be used for such things. There's an excellent article on correct and incorrect usage of eval:

@Alexei Levenkov 2015-02-26 01:59:43

@AndyE consider updating "recent versions" and "current IE TP" with some more specific time like "Versions later than XXX" or "after 2014-mm" (I'd make change myself, but I don't know what good values would be.

@wasabigeek 2018-03-10 14:52:13

for ES6, is there a way to leave out the property if the key is null/undefined? For example, in {[key] : "value"}, if key was null, it would give { null: "value"}, whereas I'd like the result to be {}

@hugemeow 2018-04-13 22:41:49

wonderful solution, but why you know so much, even reading the whole specification could not get point:(

@Benny Neugebauer 2017-10-09 18:29:06

Given code:

var thetop = 'top';
    { thetop : 10 }, 10


var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

var thetop = 'top';
var config = { [thetop] : 10 }; // = 10
<something>.stop().animate(config, 10);

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
); // = 10
<something>.stop().animate(config, 10);

@Vaishali 2017-05-13 09:30:30

Adding square bracket around the variable works good for me. Try this

var thetop = 'top';
    { [thetop] : 10 }, 10

@Oliver 2017-05-13 09:57:40

This won't work in older versions of EcmaScript, but nowadays this is a very clean approach.

@Phil M 2014-01-10 10:42:26

I have used the following to add a property with a "dynamic" name to an object:

var key = 'top';
   (function(o) { o[key]=10; return o;})({left: 20, width: 100}),

key is the name of the new property.

The object of properties passed to animate will be {left: 20, width: 100, top: 10}

This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!

Related Questions

Sponsored Content

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

57 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5832573 View
  • 7273 Score
  • 79 Answer
  • Tags:   javascript arrays

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

19 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

Sponsored Content