By Mark Renouf


2011-02-11 11:21:46 8 Comments

Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?

In code:

// Given:
var foo = {'bar': 'baz'};

// Then
var x = foo['bar'];

// vs. 
var x = foo.bar;

Context: I've written a code generator which produces these expressions and I'm wondering which is preferable.

11 comments

@Aron Rotteveel 2011-02-11 11:26:48

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["ダ"] (more examples).

Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

@Quentin 2011-02-11 11:31:07

The code examples and wording of the summary look awfully familiar. dev-archive.net/articles/js-dot-notation

@Aron Rotteveel 2011-02-11 11:32:18

No need in re-inventing the wheel, is there? Citing it as a reference.

@MetaGuru 2013-03-06 11:24:04

But I wonder, is one faster than the other?

@David Chen 2013-05-23 16:55:58

Dot notation is faster (for me at least) test your browser jsperf.com/dot-notation-vs-bracket-notation/2

@piskebee 2015-06-09 07:40:38

What does this mean... The second advantage of square bracket notation is when dealing with variable property names.? So we can use custom variable myControlNumber or i for myForm["myControlNumber" + i]?

@OJFord 2015-07-09 09:56:01

Also, [] can resolve an otherwise ambiguous parse (without the need for () as well as .) - consider obj1.obj2.foo = bar vs. obj1[ obj2.foo ] = bar

@Ryan Watts 2015-08-07 22:11:25

Great example. I've used bracket notation a lot , and was not sure of the true purpose over dot notation. Now with this example it is clear to see the big picture.

@Austin France 2015-08-12 15:44:59

in chrome 44 on my machine bracket notation is faster

@Cerbrus 2015-09-10 14:30:34

That said, using periods and square brackets in a property is just... Yikes.

@daemonexmachina 2016-01-20 08:33:07

@chenghuayang That is a little confusing, isn't it? It means property names that vary. So in the example the object myForm is assumed to have ten properties, called myForm.myControlNumber0...myForm.myControlNumber9, each of which is acted on by someFunction. Rather than go through them one at a time, a line of code per property, they can be looped over because their names vary from each other in a predictable way.

@Abdul 2016-12-08 16:56:52

@chenghuayang When you want to access a property of an object who's key is stored in a variable, you can't with dot notation.

@Amitesh 2017-08-04 07:55:34

dot notation makes debugging easier as you can hover over the property to see the value while with bracket notation debugger cant evaluate it on hover.

@Nathan 2017-08-23 14:22:48

My rule of thumb is to use bracket notation if accessing properties programmatically (variables) and use dot notation when I'm typing in known or expected property names.

@danpop 2017-10-06 12:28:42

On Firefox 56 there are almost the same.

@Dimitris Efst 2018-11-19 19:41:11

Guys,I get it. The problem is I need to access a parameter that comes from the back-end. So I did this `<pre>{{ Ctrl.api.["something.else'] | json</pre>. The else has a name property. How do I access that...?

@SherylHohman 2019-01-30 18:50:37

Link is broken. Do you have another source, or should the link be removed ? (PS thanks for including information from the link. This is a perfect example to those who post "link-only" answers, as to why such answers are discouraged, and should be deleted/removed, OR updated to include the relevant info.) I also appreciate that you cited your reference !! :-) References are super helpful for following up and additional research, when necessary.

@Bhunnu Baba 2019-05-06 13:08:31

But we can mix to dot notation and square bracket notation.

@Harunur Rashid 2018-06-07 09:59:47

You have to use square bracket notation when -

  1. The property name is number.

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  2. The property name has special character.

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  3. The property name is assigned to a variable and you want to access the property value by this variable.

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    

@Sagar Munjal 2017-07-18 17:47:49

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.

In case of Arrays

The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length because that is easier to write than array["length"].

@Limpuls 2017-11-19 15:04:55

Could you elaborate more on array.length? You say that properties accessed by dot notation are not evaluated so in case of array.length wouldn't it give us "length" string instead of evaluated value, in this case the number of items in array? The elements in an array are stored in properties this is what confuses me. What do you mean by stored in properties? What are properties? In my understanding array is just bunch of values without properties. If it they are stored in properties, how come it is not property: value/associative array?

@chessweb 2018-11-01 01:39:01

This answer is particularly valuable because it explains the difference between the two notations.

@Manish Waran 2017-05-01 04:43:00

Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.

@Anshul 2016-12-09 13:42:13

Case where [] notation is helpful :

If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -

var a = { 1 : 3 };

Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.

@Álvaro González 2011-02-11 11:25:55

You need to use brackets if the property names has special characters:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).

@user2593104 2014-04-25 07:11:26

Be careful while using these notations: For eg. if we want to access a function present in the parent of a window. In IE :

window['parent']['func']

is not equivalent to

window.['parent.func']

We may either use:

window['parent']['func'] 

or

window.parent.func 

to access it

@Lev Stefanovich 2014-02-19 01:52:52

Bracket notation can use variables, so it is useful in two instances where dot notation will not work:

1) When the property names are dynamically determined (when the exact names are not known until runtime).

2) When using a for..in loop to go through all the properties of an object.

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

@Benjamin Crouzier 2013-10-04 09:26:15

Dot notation does not work with some keywords (like new and class) in internet explorer 8.

I had this code:

//app.users is a hash
app.users.new = {
  // some code
}

And this triggers the dreaded "expected indentifier" (at least on IE8 on windows xp, I havn't tried other environments). The simple fix for that is to switch to bracket notation:

app.users['new'] = {
  // some code
}

@Ilyas karim 2018-04-12 09:57:57

Helpful answer. Thank You.

@naiquevin 2011-02-11 11:27:58

The bracket notation allows you to access properties by name stored in a variable:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

obj.x would not work in this case.

@CdB 2011-02-11 11:32:28

Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like

var x = elem["foo[]"]; // can't do elem.foo[];

This can be extended to any property containing special characters.

Related Questions

Sponsored Content

52 Answered Questions

[SOLVED] Create GUID / UUID in JavaScript?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1512625 View
  • 3696 Score
  • 52 Answer
  • Tags:   javascript guid uuid

72 Answered Questions

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

79 Answered Questions

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

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

38 Answered Questions

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

55 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

26 Answered Questions

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

Sponsored Content