Javascript dot notation versus bracket notation

Javascript dot notation versus bracket notation

Javascript is one of those fun and unique languages that let you do things differently, just because. An example of this is the javascript object model.

Most people will tell you that in javascript, everything is an object. That is not true, but the way javascript behaves fools you into thinking it is.

More on that next time - I am not here to tell you what a javascript object is not, but rather what it is.

An object in javascript is simply a hashmap of key-value pairs where the key is always a string and the value can be anything including a string, an array, a function, or even other objects.

Because you are talking about a key-value pair hashmap, you can reference those values a number of different ways.

Firstly, lets create our object. There are two primary ways to create an object in javascript and there is technically no difference in that they do exactly the same thing so it is easiest to just think of {} as a shortcut for new Object().

var obj = {};
var obj = new Object();

The primary difference between those two is that the literal notation {} takes less space, is more recognizable as to what is happening, cannot be overridden by other code, and more importantly, allows you to assign values to keys at time of object initialization. Example; here we have an initialized object with two properties foo and baz already set.

var obj = { 'foo' : 'bar', 'baz' : false }

But how do we access the methods and properties of an object correctly?

There are two ways of accessing object members, "dot notation" and "bracket notation".

// Dot notation
// Bracket notation

There are key differences between the two methods, and right times to use both.

Dot Notation

Dot notation only works with property names which are valid identifier names. An identifier must start with $, _, or any character in the Unicode categories "Uppercase letter (Lu)", "Lowercase letter (Ll)", "Titlecase letter (Lt)", "Modifier letter (Lm)", "Other letter (Lo)", or "Letter number (Nl)". (The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories "Non-spacing mark (Mn)", "Spacing combining mark (Mc)", "Decimal digit number (Nd)", or "Connector punctuation (Pc)".)

That means you have a lot of options for valid key names, but also a lot that are not valid. You have a pretty high potential for breakage if you are new to the language and are unfamiliar with what is allowed and not allowed in identifiers.;      // valid
obj.for;      // valid even though for is a reserved word ***
obj.4;        // invalid - identifiers cannot start with numbers
obj.4foo;     // invalid - identifiers cannot start with numbers;  // invalid - '-' is not a valid character for identifiers

*** Older versions of IE will error even though its legal

Bracket Notation

Bracket notation expects an expression which evaluates to a string (or can be coerced into a string), so you can use any character sequence as a property name.

obj['foo'];       // valid
obj['for'];       // valid - reserved words, are just words.
obj[4];           // valid - only a number, not an issue!
obj['4foo'];      // valid - starting with a number, no problem
obj['foo-bar'];   // valid - '-' is no longer an issue
obj[foo];         // valid - will evaluate out foo and use it is value as the property name - cannot do this with dotnotation at all.

Note; this is also why you must use bracket notation to access array elements; Identifiers cannot start with (or consist only of) numbers.

Which is better and why?

That really depends on personal preference and coding styles. Most people use dot notation exclusively because it is much easier to read and avoid any of the potential issues with identifier names simply because they know the rules.

For reading and writing code, Dot Notation is clearly faster and easier. But when it comes to code execution, Bracket notation is the faster performer. And double quotes are faster than single;

var == 1;     // fast - about 2% slower than bracket notation
var obj['foo'] == 1;  // faster - slightly slower than double quotes
var obj["foo"] == 1;  // fastest - speed!

The speed differences are minor at best but it is something to take into consideration if you need to eek out every possible bit of speed.

In the end I think the right way to go is to always use dot notation where possible, simply because it makes the code easier to read and maintain, and use bracket notation where you have to break the dot notation rules.


Categories: Software Development | Tags: javascript

Portrait photo for Jason Ellis Jason Ellis

The CTO of Grok Interactive and is a calm, considerate problem solver that has been working as a software engineer in the industry for over 15 years. He enjoys rapid application and web development and has created all manner of rich web applications using RoR, PHP, JS, Java, JSON, XML, AJAX, XHTML, CSS and every other trendy acronym you care to mention.



We provide a free consultation to discover competitive advantages for your business. Contact us today to schedule an appointment.