Switch Statement

Simple example of how to use a switch statement

by Marcel Ferdinand

HTML

<label>Enter Your Age</label>
<input id="input" type="text" />
<input id="submitBtn" type="submit" />
<div class="output"></div>

CSS

.output {
    width:300px;
    height:100px;
    background-color:#dcdcdc;
    margin-top:20px;
    padding:20px;
}

JavaScript

var output = document.querySelector('.output');

document.querySelector('#submitBtn').onclick = function () {

    var age = parseInt(document.querySelector('#input').value);
    var message = "";

    switch (true) {
        case (age < 5):
            message = "Less than 5";
            break;
        case (age > 5):
            message = "More than 5";
            break;
        default:
            message = "5";
    }
    output.innerHTML = message;

};