10/30 What's the difference


#1

THIS CODE DELIVERS THE RESULT

var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

// write a for-in loop to print the value of nyc's properties
for (var prop in nyc)
{
var x = prop;
console.log(nyc[x]);
}

WHILE THIS ONE SHOWS THE ERROR. WHAT'S THE REASON WHEN BOTH MEANS THE SAME...

var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

// write a for-in loop to print the value of nyc's properties
for (var prop in nyc)
{
console.log(nyc.prop);
}


#2

Both can be used.
The first method is called dot notation and the second method is called literal notation


#3

I understand the basic difference but the problem is, in the second code the compiler is skipping the first element. Means it's not printing the fullName and showing the error.


#4

What does the error tell ?


#5


#6

To me the dot notation inside the parentheses:

console.log(nyc.prop);

reads as if you're trying to access values of a key called "prop" in the nyc object which is not part of nyc.
If you want to use prop as a variable for the for loop try:

console.log(nyc[prop]);

brackets should create the right kind of connection.


#7

Thanks man. Appreciate your efforts to answer.