A function written in JavaScript is a block of code designed to perform a specific action.

Executes when a function written in JavaScript is called.

  function add(number1, number2) {
    return number1 + number2;
  }
  console.log(add(10, 5));

Creating a function

The function keyword is defined by a space function name and parentheses.

Function names can contain letters, numbers, underscores, and dollar signs. (same as variable definition rules)

Multiple parameters are separated by commas in parentheses. (param1, param2, param3, … )

Function codes is written inside curly braces {}.

function name(param1, param2) {
  // code
}

Function parameters are variables created for use in function codes.

Function parameters take value after the function call.

Function parameters are defined as local variables within the function.

Functions in JavaScript are the same as a procedure, a subroutine, in other programming languages.

Calling a function

In order for function codes written in JavaScript to work, function calling or function execution is required.

Ways to run JavaScript functions

  • When an event occurs – when the user clicks on the HTML object:
<button onclick="alert('Hello JavaScript!');">Click me!</button>
  • When a function is called:
function notification(message) {
  alert(message);
}

notification("Hello JavaScript!");

Function return value

JavaScript function codes stop working when it hits the return keyword.

Function returns values with the return keyword.

var result;
function add(number1, number2) {
  return number1 + number2;
}
result = add(10, 5);
alert(result);