Coding for Kids

Objects: Configuring Properties

There's an official way to add properties to an existing object. It's a lot more complex and it has a lot you can do with it. It's useful for controlling different aspects of objects.

writable: You can prevent the property's value from being changed.

enumerable: You can allow it (or not) to show in a for...in loop.

configurable: You can allow it (or not) be deleted and whether the other attributes (like writable) can be changed.

get/set: You can also create a get and set for the object. These make it convenient to set a value to the property and to get that value back. You would want to do it this way to make sure some other part of your program doesn't access it the wrong way. You can also use it when you need to have it do a calculation and return it, among many other things.

Example:

Here's an example for adding a hairColor property using this advanced process.

This makes the hairColor property equal to "brown" and allows the value to be changed, to be used in a loop, and to have its properties deleted and such.

This particular example actually does the exact same thing as just using student.hairColor = "brown";. However, it should give you an idea that you could change these things if you wanted to.

If you set enumerable to false and then ran a for...in loop on student, the you wouldn't see the hairColor property appear. It's still there; you just wouldn't see it in the loop. This would be a good way to make sure some properties don't accidentally get changed if you loop through properties a lot in some of your programs.

This process allows for greater control for larger projects and advanced coding.

You're fully configured for your next challenge!

—Dr. Wolf