Functions

Learn how to create reusable, organized, and efficient blocks of code with functions — one of the most powerful features in JavaScript.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

🏭 Real-World Analogy: Functions are like machines in a factory :

🧠 What Are Functions?

A function is a reusable block of code that performs a specific task.

Instead of writing the same code multiple times, you can write it once, give it a name, and then call it whenever you need it.

Concept

What It Means

Factory Analogy

Parameters

Values you pass in

Raw materials

Function body

The code that runs

The assembly line

Return value

What comes back

The finished product

🧩 Basic Structure

You can then call the function by writing its name followed by parentheses () :

💬 Example 1: Simple Function

The code inside the function runs only when you call it.

⚙️ Function with Parameters (Input Values)

Parameters are like "placeholders" that let you pass values into your function.

💡 Think of parameters as inputs and the function as a machine that uses those inputs to produce something.

🧮 Return Values

Sometimes you don't just want to print something — you want to return a result you can use elsewhere in your program.

The keyword return sends a value back to the part of the code that called the function.

💡 A function can only return one value — but that value can be anything: a number, string, object, or even another function.

🔄 Real-World Analogy

📦 Example 2: Function That Returns a Message

⚡ Arrow Functions — Modern JavaScript Style

Arrow functions are a shorter syntax introduced in ES6 (modern JavaScript).

If your function has only one line and returns something, you can make it even shorter:

💡 No return or needed in one-line arrow functions — it returns automatically!

💡 Example 2: Double a Number

🧰 Default Parameters

You can give parameters default values that are used if the caller doesn't provide one.

💡 This makes your code safer — it prevents errors if someone forgets to pass an argument.

🧩 Example: Default Value with Math Function

🧠 Function Scope — Where Variables Live

Variables created inside a function are only available inside that function. This is called local scope .

💡 Use local variables inside functions to avoid conflicts with other parts of your program.

🧩 Combining Functions Together

You can use one function inside another — this is called function composition .

This helps break down complex logic into smaller, reusable pieces.

🔁 Example: Real Use Case — Discount Calculator

🧩 Modular logic: The same function can calculate discounts for any product, just by changing the parameters.

🧠 Why Functions Are Essential

Functions are the building blocks of all modern apps and websites.

📜 Example: Function for Greeting Users

🔄 Function Expressions vs Declarations

You can also store functions inside variables.

💡 Both work the same, but arrow functions and function expressions are better for modern coding.

🧩 Functions Can Return Anything

A function can return numbers, strings, arrays, objects, or even other functions!

🧠 Advanced Example — Function Returning a Function

💡 This is called a closure — a powerful concept you'll learn later in advanced lessons.

🧱 Best Practices for Functions

Return instead of printing if you need to use the result somewhere else.

Keep variables local whenever possible to prevent conflicts.

⚙️ Common Mistakes to Avoid

❌ Overusing global variables — causes hard-to-track bugs.

🎯 Practice Challenge

Create these functions to test your understanding:

1️⃣ A function that converts Celsius to Fahrenheit

2️⃣ A function that checks if a number is even

3️⃣ An arrow function that finds the maximum of two numbers

4️⃣ A function with default parameters that creates a greeting message

💬 Recap

💡 Final Thought

If variables are the nouns of programming, functions are the verbs — they do things.

Mastering functions gives you the power to automate and create truly dynamic apps!

(Experiment with creating your own functions and try combining them to build mini tools!)

📋 Quick Reference — Functions

Syntax

Declaration

function greet(name) { ... }

Arrow function

const greet = (name) = > { ... }

return a + b;

Default param

function greet(name = "Guest")

Short arrow

const double = x = > x * 2;

Lesson 3 Complete — JavaScript Functions!

You can now write reusable code with parameters, return values, arrow functions, and default arguments.

Up next: DOM Manipulation — use JavaScript to modify HTML and bring your webpages to life! 🎨

Practice quiz

What does a function return if it has no return statement?

  • null
  • 0
  • undefined
  • NaN

Answer: undefined. A function with no return statement returns undefined.

Given 'function add(a, b) { return a + b; }', what does add(5, 3) evaluate to?

  • 53
  • 8
  • undefined
  • '5 + 3'

Answer: 8. return a + b sends back 5 + 3, which is 8.

Which is the correct arrow function equivalent of 'function greet(name) { console.log(name); }'?

  • const greet = (name) => { console.log(name); };
  • const greet = name { console.log(name); };
  • function greet => (name) { console.log(name); };
  • greet = => (name) console.log(name);

Answer: const greet = (name) => { console.log(name); };. Arrow functions use the (params) => { body } syntax stored in a variable.

For the one-line arrow function 'const double = (num) => num * 2;', what does double(10) return?

  • 12
  • 100
  • 20
  • undefined

Answer: 20. A one-line arrow function returns its expression automatically, so num * 2 gives 20.

In a one-line arrow function like 'const add = (a, b) => a + b;', what is true?

  • You must write the return keyword
  • It returns the expression automatically with no return or braces
  • It cannot take parameters
  • It always returns undefined

Answer: It returns the expression automatically with no return or braces. One-line arrow functions return their expression automatically, with no return keyword or braces needed.

Given 'function power(base, exponent = 2) { return base ** exponent; }', what does power(5) log?

  • 10
  • 5
  • 25
  • 32

Answer: 25. exponent defaults to 2, so 5 ** 2 = 25.

With 'function greet(name = "Guest") {...}', what is name when you call greet() with no argument?

  • undefined
  • Guest
  • null
  • an empty string

Answer: Guest. The default parameter value 'Guest' is used when no argument is passed.

Variables created inside a function are only available inside that function. What is this called?

  • Global scope
  • Local scope
  • Block hoisting
  • Closure scope

Answer: Local scope. Variables declared inside a function have local scope and exist only inside that function.

Given 'function add(a,b){return a+b}' and 'function square(num){return num*num}', what does square(add(2, 3)) log?

  • 10
  • 13
  • 25
  • 36

Answer: 25. add(2, 3) is 5, and square(5) is 5 * 5 = 25.

What is wrong with calling a function by writing just 'greet;' instead of 'greet();'?

  • It causes a syntax error
  • It does nothing — it does not call the function
  • It calls the function twice
  • It returns the function's name as a string

Answer: It does nothing — it does not call the function. Without parentheses the function is not invoked, so nothing runs; you need greet() to call it.

Continue this course