Type Coercion - Exercise

Contact Us or call 1-877-932-8228
Type Coercion - Exercise

Type Coercion

Duration: 5 to 10 minutes.

In this exercise, you will debug and fix a simple script.

  1. Open AdvancedTechniques/Exercises/type-coercion.html in your editor.
  2. Determine what is wrong with the code and fix it.
  3. Be sure to test your solution in the browser.

Solution:

AdvancedTechniques/Solutions/type-coercion.html
---- C O D E   O M I T T E D ----

var answer = prompt("What is 10-10?","");
if (answer === "0") {
	alert("Right!");	
} else {
	alert("Wrong!");
}
---- C O D E   O M I T T E D ----

This is actually trickier than it looks. In the original file, if the user presses OK on the prompt without entering anything, the alert will read "Right!" That's because an empty string is falsy and so is 0.

At first, you might think that all you need to do is change the double equals to a triple equals to account for the different types. But if you test that solution, you will find that you always get the "Wrong!" answer, even if you enter "0".

The problem is that the value entered in the prompt is a string and the string "0" does not strictly equal the number 0. That's why you have to change the condition to answer === "0".

Next