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 trial

JavaScript Create an Object Literal

Taig Mac Carthy
Taig Mac Carthy
8,139 Points

Why is he not defining the variable inside the for in loop?

This is what I did:

for (var prop in book) {
  console.log( prop + ": " + book[prop])
}

Since the variable prop is not previously defined, I had understood from this course that you had to add var inside the for in lop. However, his solution was:

for (book_property in book) {
  console.log( book_property + ": " + book[book_property])
}

Without the var. Would someone please be kind enough to explain?

JavaScript allows variable declaration without var keyword however, ou must assign a value when you declare a variable without var keyword. Now, this is not recommended because It can accidentally overwrite an existing global variable. I don't know if that helps.

1 Answer

Steven Parker
Steven Parker
229,732 Points

This is what is called "implicit global declaration". While allowed by the syntax, it is not considered good programming practice and was probably not intended by the instructor (but easily overlooked because it did not generate an error).

You can guard against this by putting the interpreter into "strict" mode where implicit declarations are not allowed and will cause an error.

To use "strict" mode, place a line like this at the beginning of the program:

"use strict";  // put interpreter into strict mode
Taig Mac Carthy
Taig Mac Carthy
8,139 Points

This is very insightful, thanks so much Steven.

Is this an example of implicit global declaration or am I misunderstanding? "Prod" is not defined and I guess it is "implied" that the function should pull from that object since its the only one that exists?

function addInventory(prod, val) {
  prod.inventory += val;
  console.log(val + " " + prod.name + "s added to the inventory.");
  console.log(prod.inventory + " " + prod.name + "s in stock.");
}```

But what if I make another object? How would the function know to pull data from the correct object unless the variables are defined?
Steven Parker
Steven Parker
229,732 Points

There are no variable declarations (implicit or otherwise) in this example. Both "prod" and "val" are parameters.

Got it, thanks so much.