MariaSzubski
8/12/2015 - 2:46 PM

Using a constructor as a template for new javascript objects.

Using a constructor as a template for new javascript objects.

// ------------------------------------- Function that will be used as a template
function Book(title, author, alreadyRead) {
	this.title = title;
	this.author = author;
	this.alreadyRead = alreadyRead;
}

// ------------------------------------- New objects created from Book()
var bookArray = [
	new Book("Dune", "Frank Herbert", false),
	new Book("Sandstorm", "James Rollins", true),
	new Book("The Maze Runner", "James Dashner", false),
	new Book("Extremely Loud and Incredibly Close", "Jonathan Safran Foer", true),
	new Book("World War Z", "Max Brooks", true),
	new Book("Armada", "Ernest Cline", false)
];

// ------------------------------------- Loop though bookArray to evaluate if the book has been read
var readCheck;
for (var i = 0; i < bookArray.length; i++) {
	if (bookArray[i].alreadyRead === true) {
		readCheck = 'You already read ';
	} else {
		readCheck = 'You still need to read ';
	}
	console.log(readCheck + '"' + bookArray[i].title + '" by ' + bookArray[i].author +'.');
}