- Ex 1:
function sayHi() {
alert( "Hello" );
}
let sayHi = function() {
alert( "Hello" );
};
function ask(question, yes, no) {
if (confirm(question)) yes()
else no();
}
function showOk() {
alert( "You agreed." );
}
function showCancel() {
alert( "You canceled the execution." );
}
// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);
------------------------------------------
ask(
"Do you agree?",
function() { alert("You agreed."); },
function() { alert("You canceled the execution."); }
);
// Function Declaration
function sum(a, b) {
return a + b;
}
// Function Expression
let sum = function(a, b) {
return a + b;
};
A Function Expression is created when the execution reaches it and is usable only from that moment. A Function Declaration can be called earlier than it is defined.
sayHi("John");
function sayHi(name) {
alert( `Hello, ${name}` );
}
sayHello("John");
let sayHello = function(name) { // (*) no magic any more
alert( `Hello, ${name}` );
};
In short, use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available, keep your global scope light, and maintain clean syntax