Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

Correct way(s) to call/trigger an anonymous function in JavaScript?

Let's say I have this function, which is like a different version of and utilizes Array.push with some different logic inside it:

var array_values = [];

function pump_array(needle, haystack, callback) {
    var pushed = false;

    if(haystack.indexOf(needle) === -1) {
        haystack.push(needle);
        pushed = true;
    }

    if(typeof callback == 'function') {
        callback(haystack, pushed);
    }
}

And now if I we use it in this manner:

var pump_array_callback = function(new_data_in_array_values, pushed) {
    if(pushed) {
        console.log('added "first" into "array_values[]"');
    } else {
        console.log('"first" already in "array_values[]"');
    }

    console.log(new_data_in_array_values);
};

pump_array('first', array_values, pump_array_callback);
pump_array('first', array_values, pump_array_callback);

The first function call of pump_array will output:

added "first" into "array_values[]"

And second will do the opposite:

"first" already in "array_values[]"

So basically, my question is:

Is this the right way to call/execute an anonymous function in a function, or elsewhere:

if(typeof callback == 'function') {
    callback(haystack, pushed);
}

And are there any other methods of doing the same, in a more pragmatic way?

Upvotes: 0

Views: 396

Answers (1)

Bergi
Bergi

Reputation: 665000

Your invocation of the callback is fine.

And are there any other methods of doing the same, in a more pragmatic way?

You should not use a callback at all for this use case. Just use a return value when you can (and you hardly ever need a callback).

function pump_array(needle, haystack) {
    if (haystack.indexOf(needle) === -1) {
        haystack.push(needle);
        return true;
    }
    return false;
}

var array_values = [];
function pump_array_result(pushed) {
    if (pushed) {
        console.log('added "first" into "array_values[]"');
    } else {
        console.log('"first" already in "array_values[]"');
    }
    console.log(array_values);
};

pump_array_result(pump_array('first', array_values));
pump_array_result(pump_array('first', array_values));

Upvotes: 2

Related Questions