How can I pass a variable as a function?

if I have this function:

   function test(x){  
   alert(x);
   }

when i run it like:

test('hello world');

i a window will appear.

good, instead of passing the parameter as a string. I need to pass the parameter as a function, for example:

   function test(x){  
   x;
   }

then I ran:

   test(alert('hello world'));

So how to pass a function as a parameter to another function?

+4
source share
1 answer

You should xactually have a function, and you should actually call it:

function test(x) {
  x();
}

test(function() { alert("Hello World!"); });

Itself alert("Hello World!")is just an expression, not a function. The only way to syntactically turn an expression into a function (without immediately evaluating it, at least) is to syntax the syntax of this function above.

+5

Source: https://habr.com/ru/post/1622381/


All Articles