3

Accessing Js object properties :

What is the difference between :

1) Obj.src
     vs
2) Obj["src"]

I only know that #1 can't be used with number ( e.g. if the property name is "1")

Is there any other major differences ?

2
  • @Dennis well , sort of duplicate. I didnt see the remark that dot notation can't be used with number. ( very important) Commented Jul 31, 2012 at 10:39
  • You're right, my bad. I assumed a link titled "characters that can't be used with dot notation" would include a list of characters that can't be used with dot notation. Commented Jul 31, 2012 at 10:48

4 Answers 4

4

No difference really. Old'ish browser showed some performance differences using either the one or the other notation, but those times are over.

The only important difference is that the bracket notation is your only chance to dynamically access Object properties.

For instance:

var access = 'src';

Obj[ access ];

you can't do that using a dot notation.

1

There is no difference between Obj.src and Obj["src"].

But when the property name is a variable, you could only use the second way to access it.

var name = "src";

Then you need to use Obj[name], Obj.name will try to access the property with the name of name.

1

In javascript, every object is an associative array.

I can't think of much more to add besides its one of the better magical features of JavaScript. :)

1

The set of properties that can be accessed with bracket notation is a superset of the properties that can be accessed with dot notation. Anything accessed with the dot must be a valid JavaScript identifier:

a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.

Properties can still be strings that are not identifiers, but require bracket notation for access:

object["I have whitespace"];
object["1startswithanumber"];
object["Punctuation!!??"];
object[""] = "empty string";
// not an exhaustive list

ES5 allows you to use reserved words as properties, x.class = "some string", however this is not allowed by ES3, so you should probably use brackets x["class"] for backwards compatability.


Bracket notation can still be used to access valid identifier properties but dot notation is considered cleaner. Brackets are generally used when you have a variable:

object[input.value];  //Retrieves the property named by the value of the input field

Functions can also be accessed with brackets:

var fn = operation == "tag" ? "getElementsByTagName":"getElementsByClassName";
document[fn](str);

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.