TypeError: Object expected?


#1

When trying to call my compare function, I get an error saying: "Oops, try again. You seem to have something wrong with your code. It threw the following error: TypeError: Object expected"

My code:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

compare(userChoice, computerChoice);

var compare = function(choice1, choice2){

if(choice1 === choice2){
	return "The result is a tie!";
}

else if(choice1 === "rock"){
	if(choice2 === "scissors"){
		return("Rock wins");
	} else {
		return("paper wins");
	}
}    
else if (choice1 === "paper"){
	if(choice2 === "rock"){
		return "paper wins";
	} else {
		return "scissors wins";    
	}
}		
else if(choice1 === "scissors"){
	if(choice2 === "rock"){
		return "rock wins";
	} else {
		return "scissors wins";    
	}   
}

}

As far as I understand, this error accures when passing a "non-JS object" to at JS function? Can someone help me spot the problem?


#2

Move that line to the end of your program, after the compare function. When written before the function it will raise a TypeError since compare() is not defined yet.


#3

Thanks! That fixed it! I didn't knew it worked like that? Like in Java, C# etc. I thought I could call the functions at anytime no matter where they were declared?


#4

That's the catch in JavaScript. Anonymous functions are expressions, not declarations. When JS fires, it does two passes through the source and parses only declared objects, but not their associated expressions. Variables and function declarations get hoisted to the top of their scope, but not values in assignments.

function foo(bar) {

}

This declaration is completely hoisted so can be run from above or below the source code since it is already parsed on the first pass. Expressions have to wait until the second pass where they are parsed from top down.


#5

Thanks for sharing that knowledge. It makes sense. I'm pretty new to web development even though I'm a 3rd year software engineering student...