Skip to content

J090 Object Usage

A dive into creating and manipulating objects using different syntax in JavaScript.

In your app.js:

Task:

  1. Create three objects (o1, o2, and o3). All objects should have two properties: firstName and lastName, both with values “a” and “b”.
  2. Add a method named fullName() to each object. This method should return the combined firstName and lastName with a space in between.
  3. Remember that the this keyword can be used to access object properties (but not inside arrow functions).
  4. The first object should be created using the [] syntax, the second using the . syntax, and the third using the {} syntax.
  5. Test the objects by printing the return values of the methods.
Solution
"use strict";

// 1. Object creation using [] syntax
let o1 = new Object();
o1['firstName'] = 'a';
o1['lastName'] = 'b';
o1.fullName = function() {
    return this.firstName + ' ' + this.lastName;
}

// 2. Object creation using . syntax
let o2 = new Object();
o2.firstName = 'a';
o2.lastName = 'b';
o2.fullName = function() {
    return this.firstName + ' ' + this.lastName;
}

// 3. Object creation using {} syntax
let o3 = {
    firstName: 'a',
    lastName: 'b',
    fullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
}

// Test objects by printing the full names
console.log(o1.fullName());
console.log(o2.fullName());
console.log(o3.fullName());

This exercise provides learners with an understanding of different methods to declare and instantiate objects in JavaScript.