reference link
function is a value. it’s not a stucture in JS
let sayHi = function() {
alert("Hello")
};
alert( sayHi ); // show code
// not run the function, because there are no parentheses in Javascript
let sayHi = function() {
alert("Hello")
};
let func = sayHi;
func(); // run function
sayHi(); // show same func()
callback function
function ask (question, yes, no) {
if(confirm(question)) yes() // confirm() true
else no() // false
}
function showOK() {
alert( "You agree." )
}
function showCancel() {
alert( "You canceled the execution." );
}
ask("Do you angree?", showOK, showCancel);
showOK
and showCancel
of ask are called callback functions or just callbacks.function ask(question, yes, no) {
if (confirm(question)) yes()
else no();
}
ask(
"Do you agree?",
function () { alert("You agreed."); },
function () { alert("You canceled the execution."); }
);
function expression vs function declaration
sayHi( "John" );
//The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.
function sayHi(name) {
alert( `Hello, ${name}` );
}
sayHi("John"); // error!
let sayHi = function(name) { // (*) no magic any more
alert( `Hello, ${name}` );
};
"use strict"
let age = prompt("What is your age?", 18);
// conditionally declare a function
if (age < 18) {
function welcome() {
alert("Hello!");
}
} else {
function welcome() {
alert("Greetings!");
}
}
// ...use it later
welcome(); // Error: welcome is not defined in strict mode
let age = 16; // take 16 as an example
if (age < 18) {
welcome(); // \ (runs)
// |
function welcome() { // |
alert("Hello!"); // | Function Declaration is available
} // | everywhere in the block where it's declared
// |
welcome(); // / (runs)
} else {
function welcome() {
alert("Greetings!");
}
}
// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.
welcome(); // Error: welcome is not defined
welcome
visibhle outside of if
?welcome
to the variable that is declarecd outside of if
and has the proper visibility.let age = prompt("What is your age?", 18);
let welcome;
if(age < 18) {
welcome = function() {
alert("Hello!");
};
} else {
welcome = function() {
alert("Greetings!");
};
}
welcome(); // ok now
Or we could simplify it even further using a quesion mark operator ?
:
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
function() { alert("Hello"); } :
function() { alert("Greeting"); };
welcome(); // ok now