freeCodeCamp Challenge Guide: Make a Person

Make a Person


Problem Explanation

You will need a closure to hold data that is not a property.

Relevant Links


Hints

Hint 1

The challenge checks for how many keys you used. Any additional variables you declare have to be in the closure of the object and not properties.


Solutions

Solution 1 (Click to Show/Hide)
const Person = function(first, last) {
  let firstName = first;
  let lastName  = last;

  this.getFirstName = function() {
    return firstName;
  };

  this.getLastName = function() {
    return lastName;
  };

  this.getFullName = function() {
    return this.getFirstName() + " " + this.getLastName();
  };

  this.setFirstName = function(first) {
    return firstName = first;
  };

  this.setLastName = function(last) {
    return lastName = last;
  };

  this.setFullName = function(first, last) {
    this.setFirstName(first);
    this.setLastName(last);
    return this.getFullName();
  };
};

const bob = new Person("Bob", "Ross");
console.log(bob.getFullName());

Code Explanation

  • Two local variables hold the two names for the object.
  • For the full name getter and setter, we use the first and last name getters/setters.

Relevant Links

71 Likes