2 min read

Functions and Scope

Functions are reusable blocks of code designed to perform a particular task. They allow you to write code once and use it many times, making programs easier to read, test, and maintain.

1. Functions

A function is executed when something invokes it (calls it).

Definition

Most languages use a keyword like function, def, or void to define a function.

  • JavaScript:
    function greet(name) {
        return "Hello " + name;
    }
  • Python:
    def greet(name):
        return f"Hello {name}"
  • C++ / Java:
    String greet(String name) {
        return "Hello " + name;
    }

Parameters vs Arguments

  • Parameters: The variables listed inside the parentheses in the function definition.
  • Arguments: The values sent to the function when it is called.

2. Return Values

Functions often return a value back to the caller. If no return statement is specified, some languages return void, None (Python), or undefined (JavaScript).

function add(a, b) {
    return a + b; // Returns the sum
}

let result = add(5, 3); // result is 8

3. Scope

Scope determines the accessibility (visibility) of variables.

Global Scope

Variables declared outside any function have Global Scope. They can be accessed from anywhere in the code.

Local (Function) Scope

Variables declared within a function are Local to that function. They cannot be accessed from outside.

Block Scope

Modern languages (like JavaScript with let/const, C++, Java) support Block Scope. Variables declared inside a block {} (like in an if statement or loop) are only accessible within that block.

if (true) {
    let blockVar = "Hidden"; // Only exists inside this if block
}

// console.log(blockVar); // Error: blockVar is not defined

programming/common-syntax programming/control-flow