Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 1 Solution

Nicolás Carrasco-Stevenson
PLUS
Nicolás Carrasco-Stevenson
Courses Plus Student 5,668 Points

A more functional approach to the challenge (AKA My solution)

I decided to write a function that would handle the creation of the student objects like this:

function newStudent (name, track, achievements, points) {
  var student = {};
  student.name = name;
  student.track = track;
  student.achievements = achievements;
  student.points = points;
  return student;
}

Then I only need to create the array and start pushing elements into it like this

var students = [];
students.push(newStudent('Joe', 'iOS Development', 3, 1000));
students.push(newStudent('Jane', 'Front-End Development', 5, 1546));

2 Answers

Colin Bell
Colin Bell
29,679 Points

You could also build it as a constructor function. Cuts down a few lines of code and opens up the possibility of branching off the Student prototype to create subclasses if needed.

function Student (name, track, achievements, points) {
  this.name = name;
  this.track = track;
  this.achievements = achievements;
  this.points = points;
}

var students = [];
students.push(new Student('Joe', 'iOS Development', 3, 1000));
students.push(new Student('Jane', 'Front-End Development', 5, 1546));
Robert Ballard
Robert Ballard
3,337 Points

Constructor functions look like an awesome way to build out clean, elegant expressions. What resources do you recommend that I check out so that I can learn more about them?