Could you explain this code for me? Thank you

       function doSomething(fn) {
           fn("Hello");
       }
       doSomething(alert);
The result of the

run is to pop up Hello
what the fn ("Hello") means here, and doSomething (alert) , which passes the alter function as an argument, but I don"t understand how it works. Also, if you use alert (doSomething) , you will output

.
function doSomething(fn) {
           fn("Hello");
       }

Please explain it in more detail, thank you

Jun.30,2021

but I don't understand how it works

first of all, functions in js are also objects and can be passed as parameters, which is a very important feature. Without this, js will be scrapped.
dosomething (alert) passes the alert function as an argument to dosometing . In the dosth interior, alert is assigned to fn . Here, fn=alert , they are the same thing. So fn ("hello") and alert behave the same.

alert (doSomething).

alert can be thought of as another way to show this behavior:

function doSomething(callback) {
    callback('Hello')
};

doSomething(console.log);

when doSomething is called, a parameter is passed as a method, and your console.log ;

is executed within the doSomething method.
Menu