Curriculum / Fundamentals / Lesson 07

Functions in JavaScript

Declarations, expressions, arrow functions — the building blocks of JavaScript.

7 of 30
beginner 📖 7 min read 🎯 4 questions

What Are Functions?

Functions are reusable blocks of code that perform a specific task. They help you avoid repetition and organize your code.

💡 Real-world analogy Think of a function as a recipe. Once you have the recipe (the function), you can follow it (call the function) as many times as you want.

Function Declarations

The most common way to define a function. It's "hoisted" to the top of its scope.

function greet(name) {
  return "Hello, " + name + "!";
}

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

Function Expressions

Assigning a function to a variable. These are not hoisted.

const greet = function(name) {
  return "Hello, " + name + "!";
};

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

Arrow Functions

A shorter syntax introduced in ES6. Great for simple functions.

const greet = (name) => {
  return "Hello, " + name + "!";
};

// Even shorter for single expressions
const double = x => x * 2;
console.log(double(5)); // 10

Parameters and Arguments

function add(a, b) { // a and b are parameters
  return a + b;
}

add(3, 5); // 3 and 5 are arguments

Return Values

The return statement sends a value back from the function. Without it, the function returns undefined.

function multiply(x, y) {
  return x * y;
}

let result = multiply(4, 3); // result = 12

Common Mistakes

Quick Quiz

1. What does the return statement do?

2. Which is NOT a way to define a function?

3. What is the output?
function test() { } console.log(test());

Summary

Back to curriculum