JavaScript Functions

Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.

Function Declaration

To create a function we can use a function declaration.

function showMessage() {
  alert( 'Hello everyone!' );
}

Function instance

function showMessage() {
  alert( 'Hello everyone!' );
}

showMessage();
showMessage();

Function Expression

let Add = function(a, b) {
  let result = a + b;

  return result;
}

Local variables

A variable declared inside a function is only visible inside that function.

function showMessage() {
  let message = "Hello, I'm JavaScript!"; // local variable

  alert( message );
}

showMessage(); // Hello, I'm JavaScript!

alert( message ); // <-- Error! The variable is local to the function

Outer variables

A function can access an outer variable as well, for example:

let userName = 'Keshab';

function showMessage() {
  let message = 'Hello, ' + userName;
  alert(message);
}

showMessage(); // Hello, Keshab

Callback functions

The function should ask the question and, depending on the user’s answer, call yes() or no():

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);

Arrow functions

let Add = (a, b) => a + b;

/* The arrow function is a shorter form of:

let Add = function(a, b) {
  return a + b;
};
*/

alert( Add(1, 2) ); // 3

Leave a Reply

Your email address will not be published. Required fields are marked *