TypeError: Cannot read property 'length' of null

Hi! I’m building a election map for a class project and I restarted my JS Bin from scratch. So what I’m trying to figure out is how do I get rid of the error. I have my method and ‘for’ loop in my factory function. Do I need to define the property with a different value than null. Here’s my snapshot: https://jsbin.com/xocapur/36/edit?js,console

Add here’s my code:

var politicianResults = function(politicianName, results, votesTotal)
{
	var politician = {};

	politician.name=politicianName;
	politician.electionResults = null;
	politician.totalVotes = 0;
	
	politician.election = function()
		{
				console.log(this.name);
		};
	
	politician.election();
	
	//Election Total Results
	
	politician.totalVotes = function()
{
	this.totalResults = 0;
	
	for(var i=0; i<this.electionResults.length; i++)
		{
			this.totalResults = this.totalResults + this.electionResults[i];
			console.log(this.totalResults);
		}
};

politician.totalVotes();
	
	return politician;
};

var jane = politicianResults("Jane Doe");
var jill =politicianResults("Jill Fawn");

	jane.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
	jill.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];

jane.electionResults[9] = 1;
jill.electionResults[9] = 28;
 
jane.electionResults[4] = 17;
jill.electionResults[4] = 38;
 
jane.electionResults[43] = 11;
jill.electionResults[43] = 27;
 
console.log(jane.electionResults);
console.log(jill.electionResults);

//Tally Up Results

jane.totalVotes();
jill.totalVotes();

console.log(jane.totalVotes);
console.log(jill.totalVotes);

why don’t you declare it as array
politician.electionResult = [] or
politician.electionResult = Array()

3 Likes

declaring it as array politician.electionResult = [] fixed this issue. Now I’m on to another problem. But thank you very much for your help.