Properties

Object’s property is a propertyName: propertyValue pair, where property name can be only a string. If it’s not a string, it gets casted into a string. You can specify properties when creating an object or later. There may be zero or more properties separated by commas.

  1. var language = {
  2. name: 'JavaScript',
  3. isSupportedByBrowsers: true,
  4. createdIn: 1995,
  5. author:{
  6. firstName: 'Brendan',
  7. lastName: 'Eich'
  8. },
  9. // Yes, objects can be nested!
  10. getAuthorFullName: function(){
  11. return this.author.firstName + " " + this.author.lastName;
  12. }
  13. // Yes, functions can be values too!
  14. };

The following code demonstates how to get a property’s value.

  1. var variable = language.name;
  2. // variable now contains "JavaScript" string.
  3. variable = language['name'];
  4. // The lines above do the same thing. The difference is that the second one lets you use litteraly any string as a property name, but it's less readable.
  5. variable = language.newProperty;
  6. // variable is now undefined, because we have not assigned this property yet.

The following example shows how to add a new property or change an existing one.

  1. language.newProperty = 'new value';
  2. // Now the object has a new property. If the property already exists, its value will be replaced.
  3. language['newProperty'] = 'changed value';
  4. // Once again, you can access properties both ways. The first one (dot notation) is recomended.