Please enable JavaScript to use CodeHS

CodeHS Glossary


Sentinel JavaScript

The SENTINEL is a constant that has the specific purpose of being the value that breaks out of a loop.

You define it at the top of a program next to the other constants in all caps like this:

var SENTINEL = 0;

The value of sentinel will usually be 0 or -1.


Example of a program that uses a SENTINEL. This program asks the user for numbers until they enter the SENTINEL. Then, it prints the sum of all the numbers they entered.

var SENTINEL = 0;

function start() {
    var sum = 0;
    while (true) {
        var num = readInt("Add a number (" + SENTINEL + " to stop).");
        if (num == SENTINEL) {
            break;
        }
        sum += num;
    }
    println("Sum: " + sum);
}

Note how it uses an if statement that breaks out of the loop when you enter the SENTINEL.

You could just use a number instead of the SENTINEL, but that would be a magic number, which is not as good style.