Conditionals, references
Exercises and the most interesting parts
1. If..else statement:
-
JavaScript file: conditionals.a_real_example_if_else_else-if.js.
-
Live example: here.
2. Switch statement:
-
JavaScript file: conditionals.a_real_example_switch_case.js.
-
Live example: here.
3. Ternary operator:
-
JavaScript file: conditionals.a_real_example_ternary_operator.js.
-
Live example: here.
4. More color choices by using switch..case statement:
-
JavaScript file: conditionals.active_learning_more_color_choices.js.
-
Live example: here.
5. Simple calendar:
-
JavaScript file: conditionals.active_learning_simple_calendar.js.
-
Live example: here.
6. The 'change'
event:
function setWeather() {...}
select.addEventListener('change', setWeather);
7. Another example wit the same onchange
event:
-
JavaScript file: globalEventHandler.onchange.js.
-
Live example: here.
<input type="text" placeholder="Type something here, then click outside of the field." size="50">
<p id="log"></p>
const input = document.querySelector('input');
const log = document.getElementById('log');
input.onchange = handleChange;
function handleChange(e) {
log.textContent = `The field's value is
${e.target.value.length} character(s) long.`;
}
8. Use Switch with expression cases. In order to create switch
..case
statement with expressions, you need to evaluate the switch’s test to true
. The following pieces of code will do the same job - reference:
// Switch..case solution - note (true)
function testScore(score) {
switch (true) {
case score > 50 && score <= 100:
console.log("Score is higher than 50");
break;
case score <= 50 && score >= 0:
console.log("Score is 50 or lower");
break;
default:
console.log("The Score is not in the range [0-100]!");
}
}
// If..else solution
function testScore(score) {
if (score > 50 && score <= 100) {
console.log("Score is higher than 50");
} else if (score <= 50 && score >= 0) {
console.log("Score is 50 or lower");
} else {
console.log("The Score is not in the range [0-100]!");
}
}