| Q1: | What happens if I compare two items of different data types (for example, a number and a string) in a conditional expression? |
|
A1:
| The JavaScript interpreter does its best to make the values a common format and compare them. In this case, it would convert them both to strings before comparing. In JavaScript 1.3 and later, you can use the special equality operator === to compare two values and their typesusing this operator, the expression will be true only if the expressions have the same value and the same data type. |
| Q2: | Why would I use switch if using if and else is just as simple? |
|
A2:
| Either one works, so it's your choice. Personally, I find switch statements confusing and prefer to use if. Your choice might also depend on what other programming languages you're familiar with because some support switch and others don't. |
| Q3: | Why don't I get a friendly error message if I accidentally use = instead of ==? |
|
A3:
| In some cases, this will result in an error. However, the incorrect version often appears to be a correct statement. For example, in the statement if (a=1), the variable a will be assigned the value 1. The if statement is considered true, and the value of a is lost. |
| Q4: | It seems like I could use a for loop to replace any of the other loop methods (while, do, and so on). Why so many choices? |
|
A4:
| You're right. In most cases, a for loop will work, and you can do all your loops that way if you want. For that matter, you can use while to replace a for loop. You can use whichever looping method makes the most sense for your application. |