14

I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'
Paul Sham
  • 3,185
  • 2
  • 24
  • 31

6 Answers6

42

You can't use variables in dot notation (short of using eval, which you don't want to do). With dot notation the property name is essentially a constant.

myObj.propName
// is equivalent to
myObj["propName"]
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • 1
    -1 as it's wrong. see my answer. `propName` in the first line is treated as a property, not a variable! – sjngm Aug 18 '11 at 05:25
  • 6
    @sjngm I disagree. @nnnnnn is not implying that `propName` is a variable, but rather the name of a property. – Zack The Human Aug 18 '11 at 05:30
  • @zack Well, then a different name would have been better. It says "is equivalent to" meaning the first line does the same thing as the third line. And that is not true. – sjngm Aug 18 '11 at 05:42
  • @zack Maybe I'm wrong, but the first time I read that answer it said `myObj[propName]`. No? Other than that I agree, it's the same. Now. – sjngm Aug 18 '11 at 05:50
  • @sjngm - Don't worry about the -1, looks like others have voted it up to compensate. I'm not sure what happened the first time you read it, but I'm sure those few lines of code are displaying as I originally typed them with the intention being that they do the same thing (if I had edited the post it would say "edited x hours ago" like Zack's does). – nnnnnn Aug 18 '11 at 07:28
  • @nnnnn If you edit the answer within a few seconds after you sent it, it doesn't say so. I already had a similar situation where the other person immediately told me that he/she had changed it and I just was too fast... – sjngm Aug 18 '11 at 08:09
  • Thanks for clarifying this. To expand, the main reason I am asking is I recently started using JS Lint and it freaks out that I'm not using dot notation. But, I guess I'll stick to square bracket for situations like this. – Paul Sham Aug 18 '11 at 13:19
  • 1
    @Paul Sham In that case you may want to try http://jshint.com/ instead. I've wrestled with JSLint for a while and sometimes I just plainly disagree with its ramblings. I'm a big fan of Crockford, but JSLint is pretty restrictive. – Zack The Human Aug 18 '11 at 23:46
9

The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

item.x // is this the property "x" or do I have to look up variable "x"?
Zack The Human
  • 8,373
  • 7
  • 39
  • 60
  • Thanks for the links to references. And yes, now that I think about it, it would be confusing. I just didn't know if there was a way. – Paul Sham Aug 18 '11 at 13:23
7

If you use numbers to access an array you have to use the brackets:

item[0]

var k = 0;
item[k]

as

item.0

doesn't work (wrong syntax).

If you use a string

item["key"]

var p = "key";
item[p]

equals

item.key

In the latter context

var p = "key";
item.p

would cause a wrong output as p is not treated as a variable here.

sjngm
  • 12,423
  • 14
  • 84
  • 114
  • Thanks, I wasn't specifically asking about a number, I just didn't think of a better identifier. But, this is good information to also know about numbers. – Paul Sham Aug 18 '11 at 13:22
4

You actually can now.

In this case you can use square brackets to use a variable for dot notation.

console.log(item.[x])

This is especially useful for use in Typescript.

dwalter
  • 111
  • 5
3

the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:

var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...
Community
  • 1
  • 1
Alex Pacurar
  • 5,801
  • 4
  • 26
  • 33
2

I made a function to set variables by dot notation, in angular 2, but this could also be used in vanilla javascript, with minor modifications.

class Utility {
    static setByDot(_obj, _path, _val) {
        return _path.split('.').reduce(function (prev, curr, _idx, _arr) {
            if ( _idx == (_arr.length-1) && prev ) {
                prev[curr] = _val;
            }

            return prev ? prev[curr] : null
        }, _obj || self);
    }
}

So you can just call

Utility.setByDot( _obj, 'foo.bar', 'value' );

And then

console.log( _obj.foo.bar );

Output, if path existed

string(6) 'value' 

If path doesnt exist, it just exits gracefully.

Karl Johan Vallner
  • 3,980
  • 4
  • 35
  • 46