3

My first question on here and need help understanding the for in loop in JavaScript.

When I run the following code I get "undefined" from the alert function:

var o = {
  a: "property 1", 
  b: "property 2", 
  c: "property 3", 
  d: "property 4"
}

for (p in o) {
  alert(o.p); 
}

but if I were to change . to [ ] (ie. alert(o[p])) the alert would return the property value as expected.

Why can't I use . to access the object property?

1
  • 3
    Because it has no way of knowing that you want to use the variable p instead of a property named p. Therfore the . operator is specifically for names of property identifiers (whether or not they exist), whereas [] is for using the result of any expression as the property name. Commented Aug 28, 2013 at 18:29

4 Answers 4

3

Imagine you have this object:

var o = {
  a: "property 1", 
  b: "property 2", 
  c: "property 3", 
  d: "property 4",
  p: "property 5"
}

and run the following:

for (p in o) {
  console.log(o.p);
}

the result will be:

property 5
property 5
property 5
property 5
property 5

Because o.p means that you want to get the value of a property named p.

Similarly in your example, the property p is not defined in your object.

If you want to get the value of a property via a string, you must use [] notation.

Sign up to request clarification or add additional context in comments.

Comments

2

o.p means the property "p" of o.

o["p"] means the same thing.

o[x] means some property (whose value is defined by variable x) of o.

o[p] the same.

Comments

2
o[p]

is p-th element in array o.

o.p

is property p of array o, which is correctly reported as undefined, as it doesn't exist.

Comments

1

If you take a closer look at this for in loop:

var obj = {
  a: "property 1", 
  b: "property 2", 
  c: "property 3", 
  d: "property 4"
}
for (var prop in obj) {
    if (typeof(prop) == 'string') {
        console.log('This is a string!');
    }
}

You will notice that the what the for in loop is giving you is the name of the property. That's why it would be ok to use obj[prop] because the property would be a string and that is a legal way to access a property of an object.

When you try and execute obj.prop it gives you undefined because property is a string that represents the name of a property, it's not the actual property.

1 Comment

Awesome, I understand now, prop is a string and thus would be like saying obj."prop" and that is not legal. obj["prop"] is legal.

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.