Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript for...in loops please explain

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?

like image 489
James Avatar asked Feb 16 '23 10:02

James


2 Answers

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.

like image 142
fardjad Avatar answered Feb 18 '23 11:02

fardjad


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.

like image 37
Patrick McElhaney Avatar answered Feb 18 '23 09:02

Patrick McElhaney