jstone jstone -3 years ago 153
Javascript Question

difference between dot notation and bracket notation in javascript

I am trying to understand the difference between

.Notation
and
[]
notation. In my problem below when I use
if (object[key] === true)
I get the correct answer. When I use
if (object.key === true)
it does not work. Could someone explain why it's different.

var myObj = {
one: false,
two: false,
three: false,
four: true,
five: false,
six: false
};
var myFunc = function (object) {
for (var key in object) {
if (object[key] === true) {
return "There is a true value in this object";
} else {

}
}
return "Sorry, there are no true values in this object";
};

Answer Source

When you use dot notation, key means the actual property in the object, which will not be there. So, undefined is returned which is not equal to true.

When you use [] notation you are accessing the property in the object with the name in the variable key. So, that will work.

For example,

var myObj = {
    myVar : 1
};

for (var key in myObj) {
    console.log(key);
    console.log(myObj.key);
    console.log(myObj[key]);
}

This will print,

myVar
undefined
1

Because, myObj has no member named key (myObj.key tries to get the member with the name key) and in the next case, myObj has a member named myVar (myObj[key] tries to get the member with the value in key).

Dot Notation

jslint prefers dot notation.

[] Notation

This offers flexibility. You can dynamically access the members with a variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download