Function expressions
- As the function creation happens in the context of the assignment expression (to the right side of
=
), this is a Function Expression:let sayHi = function() { alert( "Hello" ); }; // note that Function Expressions have a semicolon `;` at the end
- Please note, there’s no name after the
function
keyword. Omitting a name is allowed for Function Expressions. - Here we immediately assign it to the variable, so the meaning of these code samples is the same: "create a function and put it into the variable
sayHi
". - No matter how the function is created, a function is a value.
- Best example to demonstrate function expressions:
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);
- The arguments showOk and showCancel of ask are called callback functions or just callbacks.
Function Expression | Function Declaration |
---|---|
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. |
When a Function Expression is within a code block, it’s visible everywhere. | In strict mode, when a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it. |