JavaScript Basics: Understanding Functions


What Is a Function?

A function is a block of code that you can name and run whenever you need it. Functions help keep your code organized, reusable, and easy to read.

Here’s a simple example:

function sayHello(name) {
  console.log(`Hello, ${name}!`);
}

sayHello("Alice"); // → Hello, Alice!

The word function starts the definition. Inside the parentheses, we list parameters—placeholders for values we’ll give the function.
Here, name is only used inside the function (this is called local scope).


Understanding Scope

Scope decides where a variable can be used.
A variable created inside a function only works inside that function.

let message = "Global message";

function showMessage() {
  let localMessage = "Local message";
  console.log(message);      // Works! From outer scope
  console.log(localMessage); // Works! From this function
}

showMessage();
// console.log(localMessage); // ❌ Error – not visible here

Functions can also be nested (one inside another). Inner functions can see variables from the outer one.


Functions as Values

In JavaScript, functions are just like any other value—you can store them in variables or even change them later.

let launch = function() {
  console.log("Launching!");
};

launch = function() {
  console.log("Launch canceled.");
};

launch(); // → Launch canceled.

This flexibility lets you control what your program does at different times.


Two Ways to Create Functions

There are two main ways to write functions:

1. Function Declaration

function square(x) {
  return x * x;
}

2. Function Expression

const square = function(x) {
  return x * x;
};

Declarations are hoisted, meaning you can use them before they appear in your code.


Arrow Functions (Shorter Syntax)

Modern JavaScript gives us arrow functions, which are shorter versions of regular functions.

const sayHi = () => "Hi!";
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

Arrow functions are common in modern code because they are clean and simple.


Default and Missing Arguments

If a function is missing an argument, JavaScript sets it to undefined.
You can give parameters default values like this:

function greet(name = "stranger") {
  console.log(`Hello, ${name}`);
}

greet("Bob");  // → Hello, Bob
greet();       // → Hello, stranger

Closures (Remembering Variables)

Functions remember the variables that were around when they were created.
This is called a closure.

function wrapValue(n) {
  let localVariable = n;
  return function() {
    return localVariable;
  };
}

let wrap1 = wrapValue(1);
let wrap2 = wrapValue(2);

console.log(wrap1()); // → 1
console.log(wrap2()); // → 2

Each inner function “remembers” its own local variable, even after the outer function finishes running.


The Call Stack

When functions run, JavaScript keeps track of them in a call stack.
If a function calls another function, the new one goes on top of the stack.
When one finishes, it’s removed.

If you call a function too many times (like endless recursion), you’ll get a “stack overflow” error.


Recursion (A Function Calling Itself)

A recursive function calls itself to solve smaller parts of a problem.
For example:

function power(base, exponent) {
  if (exponent === 0) {
    return 1; // Base case
  } else {
    return base * power(base, exponent - 1); // Recursive step
  }
}

console.log(power(2, 3)); // → 8

Each call breaks the problem into smaller pieces until the base case is reached.


Pure Functions vs. Side Effects

A pure function only depends on its input and doesn’t change anything outside itself.

function add(a, b) {
  return a + b; // Pure
}

A function with side effects changes something outside its scope—like updating a global variable or writing to the screen.
Try to keep functions pure when possible. They’re easier to understand and test.


Summary

  • Functions organize code into reusable blocks.
  • Scope controls where variables exist.
  • Functions can be stored, changed, or nested.
  • Arrow functions make code shorter.
  • Closures let functions remember values.
  • Recursion is when a function calls itself.
  • Prefer pure functions for clean, predictable code.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *