Make a Person
In this freeCodeCamp algorithm we will take a look at a fundamental Object Oriented Programming concept - creating classes which allow us to generate objects.
We are given the boilerplate of an object constructor that will represent a person - to an extent - in code form. Our 'person constructor' will accept a parameter in which we provide it with a first name and last name. Our task is to then make a few different methods for it that will allow us to access and override this data:
getFullName()getFirstName()getLastName()getFullName()setFirstName(first)setLastName(last)setFullName(firstAndLast)
This object constructor will ultimately allow us to get and set either the first name, last name - or both - of this hypothetical person.
Requirements
There are a couple key requirements to point out:
The methods that take an argument must accept only one argument and it has to be a string.
Also...
These methods must be the only available means of interacting with the object.
Additionally, our code must pass these tests:
Object.keys(bob).lengthshould return6bob instanceof Personshould returntruebob.firstNameshould returnundefinedbob.lastNameshould returnundefinedbob.getFirstName()should return"Bob"bob.getLastName()should return"Ross"bob.getFullName()should return"Bob Ross"bob.getFullName()should return"Haskell Ross"afterbob.setFirstName("Haskell")bob.getFullName()should return"Haskell Curry"afterbob.setLastName("Curry")bob.getFirstName()should return"Haskell"afterbob.setFullName("Haskell Curry")bob.getLastName()should return"Curry"afterbob.setFullName("Haskell Curry")
Real-World Use Cases
This example in particular could be used to create an object model of a human within some kind of system or program. Much like any of your records that are kept at, say your doctor's office or your local library, contain an object model of you in some way, shape, or form in order to store information regarding you and your account in an organized format.
Psuedo-code
Let's think through the requirements and see how we'd approach the problem using plain English.
In our object constructor, we know that we will create a function - or constructor that will accept a parameter firstAndLast of type String.
// Create a function that constructs an object model of a person when passed in a single string of a first and last name
// Parse the input string and split it into to seperate strings, one for first name and one for last name
// Create a method that returns the full name as a single string
// Create a method that returns just the first name as a single string
// Create a method that returns just the last name as a single string
// Create a method that changes the existing first name of the object model
// Create a method that changes the existing last name of the object model
// Create a method that changes the existing full name of the object model
Solving the Algorithm
Setting up the function
Let's start out with the boilerplate that's given to us from freeCodeCamp:
var Person = function(firstAndLast) {
// Complete the method below and implement the others similarly
this.getFullName = function() {
return "";
};
return firstAndLast;
};
var bob = new Person('Bob Ross');
bob.getFullName();
Let's try to digest what exactly is going on with this boilerplate.
- There's a variable called
Personthat is equal to a function. Note that becausePersonis considered a class, it is convention to capitalize the name. Personaccepts an argumentfirstAndLastwhich is the input string where we provide the first and last name- Within the function, there's a method named
getFullName()which, through thethiskeyword, it is being added to the object itself. The object in this case isPerson, so you can access this method by callingPerson.getFullName(). - After the
Person.getFullName()method,firstAndLastis returned - A new
Personobject is initialized under the name ofboband'Bob Ross'is passed in as the argument forfirstAndLast. bob.getFullName()is called - which would return an empty string,""as the method has not been completed yet.
Whew! That was a lot. Let's move on to the next step.
Parsing firstAndLast
Since firstAndLast will contain both the first name and last name of our object model as a single string, how can we split the input so that we can work with either the first name or last name individually? 🤔
Well, lucky for us we can use the String.split() method. If you're unfamiliar with it and would like to learn more, check out this post here or view the official MDN docs.
Using String.split() we are able to quickly parse firstAndLast into two individual strings with just one line of code.
Let's take a closer look at how we can accomplish this:
var Person = function(firstAndLast) {
// Complete the method below and implement the others similarly
var fullName = firstAndLast.split(' ');
console.log(fullName); // outputs ["Bob", "Ross"]
this.getFullName = function() {
return "";
};
return firstAndLast;
};
var bob = new Person('Bob Ross');
bob.getFullName();
Test this code in your browser console
Awesome! 👍 If you tested the code above in your browser console you would've seen an output like this: ["Bob", "Ross"].
Setting up the 'getter' methods
The 'getter' methods are methods on our Person object that return us data. They can definitely be very handy, so let's take a look 👀 at how we can set them up.
this.getFullName()
We need to create a method that returns us the full name of our Person:
this.getFullName = function() {
return fullName.join(' '); // joins the fullName array into a single string
};
this.getFirstName()
Since we have the fullName array that contains ["Bob", "Ross"], we can access the first name of our Person ("Bob") as fullName[0]:
this.getFirstName = function() {
return fullName[0]; // returns "Bob"
};
this.getLastName()
We can then access the last name of our Person in essentially the same way:
this.getLastName = function() {
return fullName[1]; // returns "Ross"
};
Setting up the 'setter' methods
As you might imagine, the 'setter' methods allow us to alter the data within our Person class. These methods will need to be slightly more involved as in order to change an existing piece of data, we need to create a method that requires new data to be passed into it.
this.setFirstName(NewFirst)
Lets create a method that passes in a new first name, newFirst and updates fullName accordingly:
this.setFirstName = function(newFirst){
fullName[0] = newFirst; // sets the first name to newFirst
return fullName.join(' ');
}
this.setLastName(newLast)
Next - create a method that passes in a new last name, newLast and updates fullName accordingly:
this.setLastName = function(newLast){
fullName[0] = newLast; // sets the last name to newLast
return fullName.join(' ');
}
this.setFullName(newFirstAndLast)
Lastly, we will do the same thing, but this time we will be setting the full name to newFirstAndLast.
this.setFullName = function(newFirstAndLast) {
fullName = newFirstAndLast.split(' '); // sets the full name to newFirstAndLast
return fullName;
}
Full Code Snippet
And there you have it! That's essential all there is to it. We created a class that allowed us to generate new instances of our Person object on the fly. Each instance of Person contains built-in methods that allow end-users to change and view the Person's name!
var Person = function(firstAndLast) {
// Complete the method below and implement the others similarly
var fullName = firstAndLast.split(' ');
this.getFullName = function() {
return fullName.join(' ');
};
this.getFirstName = function() {
return fullName[0];
}
this.getLastName = function() {
return fullName[1];
}
this.setFirstName = function(newFirst){
fullName[0] = newFirst;
return fullName.join(' ');
}
this.setLastName = function(newLast){
fullName[1] = newLast;
return fullName.join(' ');
}
this.setFullName = function(newFirstAndLast) {
fullName = newFirstAndLast.split(' ');
return fullName.join(' ')
}
};
var bob = new Person('Bob Ross');
bob.getFullName(); // returns 'Bob Ross'
bob.getFirstName(); // returns 'Bob'
bob.getLastName(); // returns 'Ross'
bob.setFirstName("Robert"); // returns "Robert Ross"
bob.setLastName("Plant"); // returns "Robert Plant"
bob.setFullName("Robert Herjavec"); // returns "Robert Herjavec"
Recap
We got to try our hand at a fundamental Object Oriented Programming concept where we created a class that can generate reusable objects that come pre-packaged with a lot of ready-made methods. Whether you do var bob = new Person('Bob Ross'); or var elon = new Person('Elon Musk');, they will both have access to the different methods we created such as elon.getFullName() or bob.setFirstName("Robert").
This is an amazing way to create and structure highly reusable code - give yourself a pat on the back!
Shoot me an email at tim@timwheeler.com with any questions and if you enjoyed this, stay tuned and subscribe below! 👇