HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task. It is executed when "something" invokes it (calls it).


Function Syntax

A function is defined with the function keyword, followed by a name, followed by parentheses ().

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
  • Function Name: Can contain letters, digits, underscores, and dollar signs (same rules as variables).
  • Parameters: Names listed in the function definition.
  • Arguments: The real values received by the function when it is invoked.

Function Invocation

The code inside a function is not executed until it is invoked. A function can be invoked when:

  • An event occurs (like a user clicking a button).
  • It is called from other JavaScript code.
  • It is self-invoked (automatically).

The return Statement

When JavaScript reaches a return statement, the function will stop executing. If the function was called from a statement, JavaScript will "return" to execute the code after the invoking statement.

let x = myFunction(4, 3); // Function is called, return value will be stored in x

function myFunction(a, b) {
  return a * b; // Function returns the product of a and b
}
Why Functions? You can reuse code: define the code once, and use it many times. You can use the same code many times with different arguments to produce different results.

The () Operator

The () operator invokes the function. Accessing a function without () will return the function definition instead of the function result.

function toCelsius(f) {
  return (5/9) * (f-32);
}

let value = toCelsius(77); // Invokes the function
let definition = toCelsius; // Returns the function object

Key Points to Remember

  • A function is a reusable block of code
  • Parameters are placeholders; Arguments are real values
  • The return statement sends a value back to the caller
  • Functions help avoid code repetition (DRY - Don't Repeat Yourself)
  • Local variables declared inside a function are only accessible within that function
  • Invoking a function requires the () operator