Skip to main content

Introduction to Functions

A function is a reusable block of code designed to perform a particular task. They allow you to DRY up your code (Don't Repeat Yourself).

1. Function Declarations

The classic way to define a function. Variables defined within the parentheses () are called parameters. When you call the function and pass data into those parameters, they are known as arguments.

function greet(name) {
return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Hello, Alice!

Hoisting Note: Function declarations are fully hoisted. You can call them before they appear in the source code!

2. Function Expressions

A function can also be stored inside a variable. These are NOT hoisted, meaning you must define them before calling them.

const calculateArea = function(width, height) {
return width * height;
};

console.log(calculateArea(5, 10)); // 50

First-Class Citizens

In JavaScript, functions are "first-class citizens". This means that under the hood, functions are actually just Objects! Because of this, you can:

  • Store them in variables.
  • Pass them as arguments to other functions (Callbacks).
  • Return them from functions.