Search code examples
javascriptfunctionnested-loops

Moving code inside a function is not working


Any help will be very appreciated... I am trying to figure out how to nest loops inside of a function. If I input this into the console...

var i, arr = [1, 2, 3, 4, 5, 6];
var remove = [];
for (i = 0; i < arr.length; i++) {
        if (Number(arr[i]) != i % 2) {
            remove.push(arr[i]);
            arr.splice(i, 1);
        }
    }
console.log(remove);

it returns with the desired array, removing all the even numbers from arr. But, if I wrap it in a function, it is undefined...

var i, arr = [1, 2, 3, 4, 5, 6];
var remove = [];

function reject() {

    for (i = 0; i < arr.length; i++) {
        if (Number(arr[i]) != i % 2) {
            remove.push(arr[i]);
            arr.splice(i, 1);
        }
    }
};


console.log(remove);

What am I doing wrong?


Solution

  • When code is not in a function, every line in the script is executed as it is interpreted (roughly speaking).

    If you wrap some code inside a function, you have to call the function for it's effects to be applied.

    Also, you should try and keep some variables inside the function, for example your i counter could be local to the function instead of the global scope of the function.

    Therefore, use the function name to apply it's effects:

    var arr = [1, 2, 3, 4, 5, 6];
    var remove = [];
    
    function reject() {
        var i;
        for (i = 0; i < arr.length; i++) {
            if (Number(arr[i]) != i % 2) {
                remove.push(arr[i]);
                arr.splice(i, 1);
            }
        }
    };
    
    reject(); // Difference here, we're calling the function.
    console.log(remove);