HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Definitions

JavaScript functions are defined with the function keyword. You can define a function as a declaration or as an expression. Each method has its own rules and use cases.


1. Function Declarations

A function declaration is the standard way to define a function. Declared functions are hoisted, meaning they can be called before they are defined in the code.

function myFunction(a, b) {
  return a * b;
}

2. Function Expressions

A function can also be defined using an expression. A function expression can be stored in a variable. These functions are often anonymous (they have no name).

const x = function (a, b) { return a * b };
let z = x(4, 3); // The variable acts as the function name
Important: Function expressions are not hoisted. You cannot call them before they are defined.

3. Self-Invoking Functions (IIFE)

Functions can be made "self-invoking," meaning they execute automatically without being called. You do this by wrapping the function in parentheses.

(function () {
  let x = "Hello!!";  // I will invoke myself
})();

4. Functions are Objects

In JavaScript, functions are objects. They have both properties and methods.

  • arguments.length — Returns the number of arguments received when the function was invoked.
  • toString() — Returns the function as a string.

5. Arrow Functions

Arrow functions allow a short syntax for writing function expressions. They do not have their own this, which makes them very useful in certain scenarios.

// Traditional
const x = function(x, y) {
  return x * y;
}

// Arrow
const y = (x, y) => x * y;

Key Points to Remember

  • Declarations are hoisted; Expressions are not
  • Anonymous functions have no name and are often used in expressions
  • IIFEs execute immediately after they are defined
  • Arrow functions provide a clean, modern syntax
  • Functions are technically objects in JavaScript
  • The Function() constructor exists but should be avoided for security and performance reasons