Understanding the prototype chain in JavaScript

I’ve been trying to solve a challenging problem on exercism.io all evening. This “grade-school” challenge is a tough one.

Given students’ names along with the grade that they are in, create a roster for the school.
So in the end you return an object with keys 1-7 and with each persons name under their grade. The idea here is to save data on the fly, which can get a bit fiddly. First of all I had to figure out how to save data on the fly, and researching that on Stack Overflow wasn’t giving me much good information. I now understand that arrays are the only JavaScript variable that are special and can hold more than one value at a time.

Now, this isn’t simple, because on each method call i.e. school.add('Blair', 2) I had to save this information in an array and then convert the completed array into an object that only contains keys 1-7.

So, for example, how would I convert:

var array = ['Blair', 1, 'James', 2, 'Paul', 1, 'Bob', 3, 'Jane', 2, 'Sam', 1]


1: ['Blair', 'Paul', 'Sam'],
2: ['James', 'Jane'],
3: ['Bob']


Furthermore, how do I call school.roster() to return the above object when school.add() is the method that saves the values into the array?

I’ll explain how… But to do so, I first need to show you how my code was initially when I thought I had to create a function like this:

function School() {
this.add = function(student, grade) {
// code my heart out
this.roster([student, grade] || {grade: student})

this.roster = function(value) {
// somehow pass the array or object from this.add to this.roster? Bad move
return value // ??

However, this would always return undefined because the values stored in the array would only be saved on the fly within the School function. Instead, the proper way to do it (I figured out) is to add these methods to the prototype chain as follows:

var School = function() {
this.arr = [];

School.prototype.add = function(student, grade) {
this.arr.push([student, grade]); // for example
School.prototype.roster = function() {

now when I do the following:

var school = new School; // create a new object with the this variable pointing towards it
school.add('Blair', 2);

It actually saves the information on the School object so I can access it anywhere on the prototype chain on the fly like so:

school.roster() // ['Blair', 2]

Still haven’t finished the challenge so I’m gonna crack on and will upload a link to it when I revisit this post.

Leave a Reply

Your email address will not be published. Required fields are marked *