0

I am in bit of a puzzle, recently I had worked on a project where use of javascript was necessary. Everything is working fine I just need to know how does it work

eg : I had a dynamic variable count, which use to get some value, lets say I get the value as var count = 6;

Now when I put this in array {count : count } I get the output as {count : 6}

Now my doubt is the output should have been { 6 : 6} as count should have been replaced with its value but it didn't happen so. Why is happening ? and how is this working properly ?

4
  • 1
    In JavaScript, that is called an object literal and it functions differently from what you may have come to understand with PHP's associative arrays. If that is literally your code {count: count} then you have assigned the variable count on the right to the key count on the left. If you had used something like theObj[count] = count, then you would have ended up with the {6: 6} you expected. Commented Jun 1, 2014 at 12:42
  • Please post the code with more context so we can see what you attempted. Commented Jun 1, 2014 at 12:42
  • You are referencing the variable with it's value in the format javascript wants it. The language just interprets it that way. Try giving us a concrete example Commented Jun 1, 2014 at 12:44
  • @MichaelBerkowski Thanks for the descriptive answer, I think I get it what you said Commented Jun 1, 2014 at 12:45

3 Answers 3

1

The key value pairs treat the key as a literal and the value as a variable.

so:

var count = 6;
var o = {count: count};  // results in {count: 6}

but to use a variable as the key, you can do this:

var count = 6;
var o = {};
o[count] = count;  // results in: {6: 6}
Sign up to request clarification or add additional context in comments.

Comments

0

The JavaScript object initialisation syntax lets you use bare words. If you do this:

{ foo: 6, bar: 12 }

It's equivalent to this:

{ 'foo': 6, 'bar': 12 }

What you want is to assign directly, like so:

var foobar = {};
foobar[foo] = 6;
foobar[bar] = 12;

Comments

0

In JavaScript associative arrays (or most associative arrays for that matter), the left side is the key, and the right side is the value. -> {key:value}

When you put {count:count} when you have a count variable beforehand (let's say its value is 10), what will happen is it will be read as {count:10}.

The left-hand side, or the key, is not a variable, but a constant.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.