Functions in JavaScript
The Core Unit of Logic, Reuse, and Abstraction
If variables store data, functions store behavior. Almost everything meaningful in JavaScript happens inside a function or because of one.
Understanding functions deeply is the difference between writing code and designing logic.
What Is a Function?
A function is a reusable block of code designed to perform a specific task.
function greet() {
console.log("Hello!");
}
You define it once. You execute it whenever needed.
Functions help you:
Think of functions as named intentions.
Functional Programming Paradigm (In Simple Terms)
Functional programming is a way of thinking where:
In JavaScript, this means:
Example:
function add(a, b) {
return a + b;
}
Input goes in. Output comes out. No hidden behavior.
This mindset leads to:
JavaScript is not purely functional, but it supports functional thinking very well.
Three Types of Functions in JavaScript
1. Function Declaration
function multiply(a, b) {
return a * b;
}
Key characteristics:
Use when:
2. Function Expression
const subtract = function (a, b) {
return a - b;
};
Key characteristics:
Use when:
3. Arrow Function
const divide = (a, b) => a / b;
Key characteristics:
Use when:
Avoid arrows when you need:
Recommended by LinkedIn
Parameters vs Arguments
This distinction is often missed.
function greet(name) { // parameter
console.log(name);
}
greet("Prince"); // argument
Think:
Returning from a Function
Functions can return values using return.
function square(x) {
return x * x;
}
Important facts:
Returning values makes functions composable.
Hoisting in JavaScript (Critical Concept)
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope.
Function Declarations Are Hoisted
sayHi();
function sayHi() {
console.log("Hi");
}
This works.
Function Expressions Are Not Hoisted the Same Way
sayHi(); // Error
const sayHi = function () {
console.log("Hi");
};
The variable exists, but the function does not.
Rule of thumb:
Variable Scope
Scope determines where a variable can be accessed.
JavaScript has:
function test() {
let x = 10;
}
console.log(x); // Error
Variables live only inside their scope.
Closures (The Most Powerful Concept Here)
A closure happens when a function remembers variables from its outer scope even after that scope has finished executing.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Why this works:
Closures enable:
Most modern JavaScript patterns are built on closures.
Common Mistakes to Avoid
Understanding scope and closures prevents subtle bugs.
Mental Model to Remember