Practice Set - Truth, Equality & JavaScript

by subsari

JavaScript

function compareCoercionDoesntWork(){
	var a = 6;
	var b = "ten"; 
	
	if (a < b || b < a) {
		alert("this is true!");
	}
}

function compareCoercionDoesntWorkExplained(){
	var a = 6;
	var b = {
		valueOf: function(){ 
			console.log("running valueOf()");
			return 10;
		},
		toString: function() { 
			console.log("running toString()");
			return "10"; 
		}
	}; 
	
	if (a < b || b < a) {
		alert("this is true!");
	}
}

function compareCoercionDoesWork(){
	var a = 6;
	var b = "10";
	
	if (a < b || b < a) {
		alert("[function compareCoercionDoesWork()] this is true!");
	}
}


//compareCoercionDoesntWork();
compareCoercionDoesntWorkExplained();
//compareCoercionDoesWork();