Objects

Frontend SELF EN
Level 36, Lesson 0
Available

6.1 Creating Objects

Objects are one of the primary data types in JavaScript and are widely used for storing and managing data. An object is a collection of properties, where each property consists of a key (name) and a value. In this lecture, we will cover creating objects, as well as accessing their properties and methods.

1. Object Literal

The most common way to create an object in JavaScript is by using an object literal.

In this example, we created an object person with four properties: name, age, isStudent, and greet.

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false,
        greet: function() {
          return 'Hello!';
        }
      };
    
  

2. Object Constructor

Objects can also be created using the Object() constructor.

This method is equivalent to creating an object using an object literal, but it's more verbose:

JavaScript
    
      let person = new Object();
      person.name = 'John';
      person.age = 30;
      person.isStudent = false;
      person.greet = function() {
        return 'Hello!';
      };
    
  

3. Constructor Function

A constructor function allows for creating multiple instances of objects with the same properties and methods.

In this example, the constructor function Person() is used to create objects john and jane with identical properties and methods:

JavaScript
    
      function Person(name, age, isStudent) {
        this.name = name;
        this.age = age;
        this.isStudent = isStudent;
        this.greet = function() {
          return 'Hello!';
        };
      }

      let john = new Person('John', 30, false);
      let jane = new Person('Jane', 25, true);
    
  

4. Object.create() Method

The Object.create() method creates a new object and immediately assigns it a prototype — another object where the new one will look for properties and methods it does not have itself.

In this example, the object john is created based on the prototype personPrototype:

JavaScript
    
      let personPrototype = {
        greet: function() {
          return 'Hello!';
        }
      };

      let john = Object.create(personPrototype);
      john.name = 'John';
      john.age = 30;
      john.isStudent = false;

      console.log(john.name);    // Outputs: John
      console.log(john.greet()); // Outputs: Hello!
    
  

Look at the last line. The object john has no greet method of its own — we only wrote name, age and isStudent into it. Yet john.greet() works: when a property is accessed, JavaScript first looks for it on the object itself, and if it is not there, moves up to the prototype. This lookup path is called the prototype chain.

The difference between an own property and an inherited one is easy to see:

JavaScript
    
      console.log(john.hasOwnProperty('name'));  // Outputs: true
      console.log(john.hasOwnProperty('greet')); // Outputs: false
      console.log('greet' in john);              // Outputs: true
    
  

hasOwnProperty() answers the question «does the object itself have this property», while the in operator answers «can this property be reached at all, even through the prototype chain». Hence the different answers for greet.

An important point: prototype properties are not copied into the new object. personPrototype stays a separate object, and john merely references it. That is why a single prototype can be shared by hundreds of objects, with greet stored in memory just once. Compare this with the constructor function in example 3: there every created object got its own copy of greet.

The second argument: properties with settings

Object.create() takes a second, optional argument — an object describing the properties to create right away. They are defined not just by a value, but by a descriptor — a set of settings:

  • value — the property value itself
  • writable — whether the value can be changed (defaults to false)
  • enumerable — whether the property shows up in for...in and Object.keys() (defaults to false)
  • configurable — whether the property can be deleted or its settings changed (defaults to false)
  • get / set — a getter and a setter instead of a plain value. The getter runs when the property is read, the setter when it is written to

Putting it all together:

JavaScript
    
      let john = Object.create(personPrototype, {
        name: {
          value: 'John',
          writable: true,        // value can be changed
          enumerable: true       // property is visible in for...in
        },
        id: {
          value: 1001,
          writable: false,       // read-only
          enumerable: true
        },
        info: {
          enumerable: true,
          get: function() {      // getter: runs when read
            return this.name + ' #' + this.id;
          },
          set: function(value) { // setter: runs when written
            this.name = value;
          }
        }
      });

      console.log(john.info);  // Outputs: John #1001

      john.name = 'Johnny';    // works
      john.id = 2002;          // silently does nothing
      console.log(john.info);  // Outputs: Johnny #1001
    
  

Note that all three flags default to false, so when the second argument is used they almost always have to be set explicitly. Assigning to a property with writable: false fails silently in sloppy mode and throws a TypeError in strict mode ('use strict').

One more useful case is Object.create(null). Such an object has no prototype at all: no toString(), no hasOwnProperty(), no other inherited methods. That makes it a handy «clean dictionary» where every key is guaranteed to be yours and not inherited from Object.prototype.

6.2 Accessing Properties and Methods

1. Dot Notation

The most common way to access an object's properties and methods is using dot notation:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        greet: function() {
          return 'Hello!';
        }
      };

      console.log(person.name);  // Outputs: John
      console.log(person.age);   // Outputs: 30
      console.log(person.greet()); // Outputs: Hello!
    
  

2. Bracket Notation

Object properties can also be accessed using bracket notation. This method is useful if the property name is stored in a variable or contains spaces or special characters:

JavaScript
    
      let person = {
        'first name': 'John',
        age: 30,
        greet: function() {
          return 'Hello!';
        }
      };

      console.log(person['first name']); // Outputs: John
      console.log(person['age']);        // Outputs: 30

      let propertyName = 'greet';
      console.log(person[propertyName]()); // Outputs: Hello!
    
  

3. Modifying and Adding Properties

Object properties can be modified or added at any time:

JavaScript
    
      let person = {
        name: 'John',
        age: 30
      };

      // Modifying an existing property
      person.age = 31;
      console.log(person.age); // Outputs: 31

      // Adding a new property
      person.isStudent = false;
      console.log(person.isStudent); // Outputs: false
    
  

4. Deleting Properties

Object properties can be deleted using the delete operator:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false
      };

      delete person.isStudent;
      console.log(person.isStudent); // Outputs: undefined
    
  

6.3 Iterating Over Object Properties

1. for...in Loop

The for...in loop allows iterating over all enumerable properties of an object:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false
      };

      for (let key in person) {
        console.log(`${key}: ${person[key]}`);
      }

      // Outputs:
      // name: John
      // age: 30
      // isStudent: false
    
  

2. Object.keys() Method

The Object.keys() method returns an array of all enumerable properties of an object:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false
      };

      let keys = Object.keys(person);
      console.log(keys); // Outputs: ['name', 'age', 'isStudent']
    
  

3. Object.values() Method

The Object.values() method returns an array of values for all enumerable properties of an object:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false
      };

      let values = Object.values(person);

      console.log(values); // Outputs: ['John', 30, false]
    
  

4. Object.entries() Method

The Object.entries() method returns an array of [key, value] pairs for all enumerable properties of an object:

JavaScript
    
      let person = {
        name: 'John',
        age: 30,
        isStudent: false
      };

      let entries = Object.entries(person);

      console.log(entries); // Outputs: [['name', 'John'], ['age', 30], ['isStudent', false]]
    
  

6.4 Checking for Property Existence

1. in Operator

The in operator checks for the existence of a property in an object:

JavaScript
    
      let person = {
        name: 'John',
        age: 30
      };

      console.log('name' in person); // Outputs: true
      console.log('isStudent' in person); // Outputs: false
    
  

2. hasOwnProperty() Method

The hasOwnProperty() method checks if an object has a specific property as its own (not inherited):

JavaScript
    
      let person = {
        name: 'John',
        age: 30
      };

      console.log(person.hasOwnProperty('name')); // Outputs: true
      console.log(person.hasOwnProperty('isStudent')); // Outputs: false
    
  
1
Task
Frontend SELF EN, level 36, lesson 0
Locked
Object Properties
Object Properties
1
Task
Frontend SELF EN, level 36, lesson 0
Locked
Modifying Properties
Modifying Properties
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION