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


let's have function, different version of , utilizes array.push 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 if use in manner:

var pump_array_callback = function(new_data_in_array_values, pushed) {     if(pushed) {         console.log('added "first" "array_values[]"');     } else {         console.log('"first" 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 output:

added "first" "array_values[]"

and second opposite:

"first" in "array_values[]"

so basically, question is:

is right way call/execute anonymous function in function, or elsewhere:

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

and there other methods of doing same, in more pragmatic way?

your invocation of callback fine.

and there other methods of doing same, in more pragmatic way?

you should not use callback @ use case. use return value when can (and hardly ever need 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" "array_values[]"');     } else {         console.log('"first" in "array_values[]"');     }     console.log(array_values); };  pump_array_result(pump_array('first', array_values)); pump_array_result(pump_array('first', array_values)); 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -