Understanding Functions in JavaScript

Functions

Functions are reusable code blocks that execute when invoked or triggered by events.

Function Syntax

function calculateTotal() {
    // Code to execute
}

The function's code executes when it is called.

Functions with Parameters

Values can be passed to functions during invocation. These values are called parameters and can be used within the function body. Multiple parameters can be separated by commas.

function calculateTotal(price, quantity) {
    // Use parameters here
}

Functions with Return Values

Functions can return values to the calling code using the return statement. When executed, return stops function execution and sends back the specified value.

function getCurrentValue() {
    const baseValue = 10;
    return baseValue;
}

const result = getCurrentValue(); // result = 10

Parentheses in Function Calls

Parenthesis are required when calling a function to execute its code. Without parentheses, you're referencing the functon object itself rather than invoking it.

  • With parentheses: Executes the function and returns its result
  • Without parentheses: References the function as an object pointer

Immediately Invoked Function Expressions (IIFE)

Anonymous functions can be defined and executed immediately using this pattern:

(function() {
    // Execution code
})();
  • First parentheses: Define the function (parameters can be included)
  • Second parantheses: Execute the function immediately
  • Outer parentheses: Ensure proper parsing and execution

This pattern creates a function scope and executes the code immediately after definition.

Tags: javascript functions programming web-development

Posted on Sat, 16 May 2026 14:15:51 +0000 by phpPunk