Skip to content

Instantly share code, notes, and snippets.

@jonaskahn
Last active March 7, 2023 05:03
Show Gist options
  • Save jonaskahn/05d761611ab8bf74292f0af65af2ec7a to your computer and use it in GitHub Desktop.
Save jonaskahn/05d761611ab8bf74292f0af65af2ec7a to your computer and use it in GitHub Desktop.
  • Ex 1:
function sayHi() {
  alert( "Hello" );
}

let sayHi = function() {
  alert( "Hello" );
};

Callback functions

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 Expression vs Function Declaration

// 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}` );
};

When

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment