javascriptWrong approach to dot notation

I have a object that looks like this:

var obj = {
   Laser: [0, 2],
   Missile: [4, 4]

using literal notation, i can access the properties just fine:

for (prop in obj){
console.log(prop + " scored " + obj[prop][0] + " out of " + obj[prop][1] + " shots.");

Why cant the same be said using dot-notation like this ?

for (prop in obj){
console.log(prop + " scored " + obj.prop[0] + " out of " + obj.prop[1] + " shots.");
-> error

thanks in advance

Because these two examples are not the same. The first one is ok:

prop == "Laser"
obj[prop] == obj["Laser"]
obj["Laser"][0] === 0

prop == "Missile"
obj[prop] == obj["Missile"]
obj["Missile"][0] == 4

In the second one you are trying to access "prop" property, which is undefined:

obj.prop == obj["prop"]
obj["prop"] === undefined
obj["prop"][0] // TypeError: Cannot read property "0" of undefined

And, btw, this has nothing to do with JSON.

When using dot notation, the prop in this case looks for an actual key named prop on the object, which it doesn't have. Take a look at this post for a more in depth difference between dot and bracket notation

I highly recommend you this awesome reading

Here is the quote from the Accessing Properties chapter:

The notations work almost identically, with the only difference being that the square bracket notation allows for dynamic setting of properties and the use of property names that would otherwise lead to a syntax error.

With the sample from this source:

var foo = {name: 'kitten'}; // kitten
foo['name']; // kitten

var get = 'name';
foo[get]; // kitten

foo.1234; // SyntaxError
foo['1234']; // works

I think it will be most simple to replace the variables with constants to see what is actually going on in each loop:

The first loop:

for (prop in obj){
    console.log(prop + " scored " + obj[prop][0] + " out of " + obj[prop][1] + " shots.");

Iteration 1:

console.log("Laser" + " scored " + obj["Laser"][0] + " out of " + obj["Laser"][1] + " shots.");

Iteration 2:

console.log("Missile" + " scored " + obj["Missile"][0] + " out of " + obj["Missile"][1] + " shots.");

The second loop:

    for (prop in obj){
console.log(prop + " scored " + obj.prop[0] + " out of " + obj.prop[1] + " shots.");
-> error

Iteration 1:

console.log("Laser" + " scored " + obj["prop"][0] + " out of " + obj["prop"][1] + " shots.");

Iteration 2:

console.log("Missile" + " scored " + obj["prop"][0] + " out of " + obj["prop"][1] + " shots.");

By using dot notation you are asking to look for a property named prop on the obj. This is obviously not what you are after.

So these are equivalent:

  1. obj.prop
  2. obj["prop"]

Simply put, prop is a string form of the property name. obj.prop in a for ... in is the same as doing obj.'Missile'.

The bracket method uses a string and compares that string with the names of the object's properties. If you don't use a string inside the brackets it will look for a variable named Missile and return a reference error because there isn't one.

var obj = {
  Laser: [0, 2],
  Missile: [4, 4]

function log(input) {
  setTimeout(function() {
  }, 1000);

log(obj['Missile']); // [4, 4]
log(obj.Missile); // [4, 4]
log(obj[Missile]); // Looks for a variable called Missile. Doesn't find it. ReferenceError: Missile is not defined
// log(obj.'Missile'); // Invalid string placement. SyntaxError: Unexpected string

Related Articles
  • I have a large JavaScript object that contains properties that are added and deleted as and when required. Something similar to this: var data = { data1: { subscribers : ["sub1", "sub2"] }, data2: { subscribers : ["sub1", &qu
  • The following line is apparently written best in dot notation. I am trying to clean my JavaScript code to make it strict. What does it mean? if (ie||ns6) { var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document
  • Looking into Kohana documentation, i found this really usefull function that they use to get values from a multidimensional array using a dot notation, for example: $foo = array('bar' => array('color' => 'green', 'size' => 'M')); $value = path($f
  • I search for a VS2010 compatable C++ linq library with C# LINQ dot sintax. meaning something like: from(...).where(...).orderBy.firstOrDefault(); I googled and found this so answer LINQ libraries collection/mess: Rx Extensions cpplinq has no orderBy
  • Softball! Is there an option to and/or how do I surpress errors like the following: 175,14:['tracker'] is better written in dot notation. SEO for this is terrible If it's a feature and not a bug, place this at the top of your file. /*jshint sub:true*
  • I am using JSON within my javascript and I am trying to get a string value for the dot notation representation. For example AAA.BBB[0].CCC.DDD[5].EEE = 123 in JSON dot notation format. But I want to get the value "AAA.BBB[0].CCC.DDD[5].EEE" as a
  • Been searching for about an hour, everything I see on dot notation is pieced out with little explanation, or it's a post of people arguing about that and bracket notation... I just want a site or book, I will buy a book... ...that has a lot of info o
  • I have a function that takes a string as an argument, my problem is that the string can be a sentence such as: "My name is John Doe. I need a car." or it can be a dot notation: "". I don't know much about regex (if
  • How can i read this data i'm getting on my page via post? This are the variables as they appear on firebug under POST. list[0].firstName =test 1 list[0].name =test list[1].name =test I know that php replaces dots with underscores so i can access some
You Might Also Like