Last Updated: February 25, 2016
·
7.814K
· daniel-hug

JavaScript thought: for...else and while...else statements

A feature that would be handy in JavaScript:
<br>
for...else statements:

// Loop through an array of people:
for (var i = 0, l = people.length; i < l; i++) console.log(people[i]);

// If we didn't enter the previous loop:
else console.log('No people! :(');

<br>
and while...else statements:

// Loop through an array of people:
var numPeople = people.length;
while (numPeople--) console.log(people[numPeople]);

// If we didn't enter the previous loop:
else console.log('No people! :(');

<br>
Here's another usage example (with for...else):

function removeKeys(object /*, keyStr1, keyStr2, etc.*/) {
    var args = arguments,
        hasOwnKey = {}.hasOwnProperty.call,
        key;

    // Loop through arguments last first not including the first argument:
    for (var numArgs = args.length; --numArgs;) {
        key = args[numArgs];
        delete object[key];
    }

    // If there was only one argument (the previous loop didn't execute):
    else for (key in object) {
        if (hasOwnKey(object, key)) delete object[key];
    }
};

<br>
and again with while...else:

function removeKeys(object /*, keyStr1, keyStr2, etc.*/) {
    var args = arguments,
        numArgs = args.length,
        hasOwnKey = {}.hasOwnProperty.call,
        key;

    // Loop through arguments last first not including the first argument:
    while (--numArgs) {
        key = args[numArgs];
        delete object[key];
    }

    // If there was only one argument (the previous loop didn't execute):
    else for (key in object) {
        if (hasOwnKey(object, key)) delete object[key];
    }
};

<br>
Thoughts?