2.4. Conditionals¶
Conditional statements in Python and JavaScript are very similar. In Python we have three patterns:
2.4.1. Simple if¶
if condition:
statement1
statement2
...
In JavaScript this same pattern is simply written as:
if (condition) {
statement1
statement2
...
}
Once again you can see that in JavaScript the curly braces define a block
rather than indentation. In JavaScript, the parenthesis around the condition
are required because if is technically a function that evaluates to True
or False.
2.4.2. if else¶
if condition:
statement1
statement2
...
else:
statement1
statement2
...
In JavaScript this is written as:
if (condition) {
statement1
statement2
...
} else {
statement1
statement2
...
}
2.4.3. elif¶
JavaScript does not have an elif pattern like Python. In JavaScript you can get the
functionality of an elif statement by nesting if and else. Here is a
simple example in both Python and JavaScript.
In JavaScript we have a couple of ways to write this
We can get even closer to the elif statement by taking advantage of the
JavaScript rule that a single statement does not need to be enclosed in curly
braces. Since the if is the only statement used in each else we can get
away with the following.
2.4.4. switch¶
JavaScript also supports a switch statement that acts something like the
elif statement of Python under certain conditions. To write the grade
program using a switch statement we would use the following:
The switch statement is not used very often, and I recommend you do
not use it! First, it is not as powerful as the else if model
because the switch variable can only be compared for equality with an
integer or enumerated constant. Second it is very easy to forget to put
in the break statement. If the break statement is left out then then
the next alternative will be automatically executed. For example if the
grade was 95 and the break was omitted from the case 9:
alternative then the program would print out both A and B.