norkuy
norkuy

Reputation: 743

Callback and incrementing variable

Why does result = array[0] or 1 and not array[1] or 2 when the callback console.logs result?

    function test(array, callback) {
        var startingIndex = 0;

        var result = array[startingIndex];

        startingIndex++;

        callback(result);

    }

        test([1, 2, 3], function(result) {
            console.log(result);
    });

Upvotes: 1

Views: 756

Answers (1)

Jonathan.Brink
Jonathan.Brink

Reputation: 25393

This is because you are incrementing the startingIndex variable before assigning the result variable.

You have:

var result = array[startingIndex];
startingIndex++;

Swap these two lines and you will get the intended result:

startingIndex++;
var result = array[startingIndex];

Upvotes: 2

Related Questions