Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHamza Saleemi
4,257 PointsNeed help understanding objects in JavaScript
In this video Dave said that the only way to access the value of a key in an object is by using the [] notation, but in the next video he uses the dot notation.
var questions = [
{
question: 'How many states are in the United States?',
answer: 50
},
{
question: 'How many continents are there?',
answer: 7
},
{
question: 'How many legs does an insect have?',
answer: 6
}
];
var correctAnswers = 0;
var question;
var answer;
var response;
function print(message) {
document.write(message);
}
for (var i = 0; i < questions.length; i += 1) {
question = questions[i].question;
answer = questions[i].answer;
response = prompt(question);
response = parseInt(response);
if (response === answer) {
correctAnswers += 1;
}
}
html = "You got " + correctAnswers + " question(s) right."
print(html);
as you can see it sats questions[i].question instead of questions.[i][question]. So which one is it? Can we accesss the value of the key using dot notation?
1 Answer
Felix Sonnenholzer
14,654 PointsHi,
when I remember correctly he said the only way to access a key in a for-in loop is with [] notation.
In a normal for loop you can access it with dot notation AND [] notation. So both are possible.
Hamza Saleemi
4,257 PointsHamza Saleemi
4,257 PointsWow second time I'm seeing you today! It makes sense to me now so thanks again!