Skip to the content.

Conditionals, references

Exercises and the most interesting parts

1. If..else statement:

2. Switch statement:

3. Ternary operator:

4. More color choices by using switch..case statement:

5. Simple calendar:

6. The 'change' event:

function setWeather() {...}
select.addEventListener('change', setWeather);

7. Another example wit the same onchange event:

<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]!");
    }
}