JavaScript Functions
Reviewed & published by Brayan K
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
- Define and call functions
- Pass parameters and get return values
- Arrow function syntax (ES6)
- Default parameter values
- Function scope and local variables
- Function composition and reusability
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
🏭 Real-World Analogy: Functions are like machines in a factory:
- • You give them inputs (raw materials / parameters)
- • They do some work (the code inside)
- • They give you an output (the return value)
- • You can use the same machine over and over with different inputs!
🧠 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 |
Functions make your code:
- ✅ Easier to read
- ✅ Easier to debug
- ✅ More efficient and modular
🧩 Basic Structure
A function typically looks like this:
function nameOfFunction() {
// code to run
}You can then call the function by writing its name followed by parentheses ():
nameOfFunction();💬 Example 1: Simple Function
function greet() {
console.log("Hello, World!");
}
greet(); // Call the functionHello, World!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.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice");
greet("Boopie");Hello, Alice!
Hello, Boopie!💡 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.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);8The 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
Imagine a coffee machine:
- • You give it inputs (water + coffee beans)
- • It does some work (heats and brews)
- • It gives you an output (coffee ☕)
That's exactly what a function does!
📦 Example 2: Function That Returns a Message
function getWelcomeMessage(user) {
return `Welcome back, ${user}!`;
}
let message = getWelcomeMessage("Brayan");
console.log(message);Welcome back, Brayan!⚡ Arrow Functions — Modern JavaScript Style
Arrow functions are a shorter syntax introduced in ES6 (modern JavaScript).
🧩 Example 1: Regular Function
function greet(name) {
console.log(`Hello, ${name}!`);
}const greet = (name) => {
console.log(`Hello, ${name}!`);
};If your function has only one line and returns something, you can make it even shorter:
const add = (a, b) => a + b;💡 No return or needed in one-line arrow functions — it returns automatically!
💡 Example 2: Double a Number
const double = (num) => num * 2;
console.log(double(10));20🧰 Default Parameters
You can give parameters default values that are used if the caller doesn't provide one.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!💡 This makes your code safer — it prevents errors if someone forgets to pass an argument.
🧩 Example: Default Value with Math Function
function power(base, exponent = 2) {
return base ** exponent;
}
console.log(power(5)); // 25
console.log(power(5, 3)); // 125🧠 Function Scope — Where Variables Live
Variables created inside a function are only available inside that function. This is called local scope.
function showMessage() {
let message = "Hello from inside the function!";
console.log(message);
}
showMessage();
console.log(message); // ❌ Error: message is not defined💡 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.
function add(a, b) {
return a + b;
}
function square(num) {
return num * num;
}
console.log(square(add(2, 3))); // (2+3)^2 = 25This helps break down complex logic into smaller, reusable pieces.
🔁 Example: Real Use Case — Discount Calculator
function calculateTotal(price, discount) {
let finalPrice = price - (price * discount / 100);
return finalPrice;
}
console.log(calculateTotal(100, 10)); // 90
console.log(calculateTotal(250, 25)); // 187.5🧩 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.
They are used for:
- • Handling user input
- • Calculating values (shopping cart totals, scores, distances, etc.)
- • Fetching data from servers (API calls)
- • Responding to events like clicks or scrolls
- • Organizing your entire app into readable parts
📜 Example: Function for Greeting Users
function welcomeUser(username) {
console.log(`Welcome to LearnCodingFast, ${username}!`);
}
welcomeUser("Boopie");Welcome to LearnCodingFast, Boopie!// Function basics
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Boopie");
greet("Alice");
// Function with return
function add(a, b) {
return a + b;
}
console.log("5 + 3 =", add(5, 3));
console.log("10 + 20 =", add(10, 20));
// Arrow function
const double = (num) => num * 2;
console.log("Double of 10:", double(10));
// Default parameters
function power(base, exponent = 2) {
return base ** exponent;
}
console.log("5^2 =", power(5));
console.log("5^3 =", power(5, 3));
// Function that returns an object
const createUser = (name, age) => ({ name, age });
console.log("New user:", createUser("Bob", 25));
// Try creating your own functions!🔄 Function Expressions vs Declarations
You can also store functions inside variables.
// Declaration
function greet() {
console.log("Hello!");
}
// Expression
const sayHello = function() {
console.log("Hi there!");
};
greet();
sayHello();💡 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!
function getUser() {
return {
name: "Brayan",
age: 16
};
}
console.log(getUser().name); // Brayan🧠 Advanced Example — Function Returning a Function
function multiplier(x) {
return function(y) {
return x * y;
};
}
const double = multiplier(2);
console.log(double(5)); // 10💡 This is called a closure — a powerful concept you'll learn later in advanced lessons.
🧱 Best Practices for Functions
function calculateTotal() { ... } // good
function ct() { ... } // badEach function should do one task only.
✅ Use arrow functions for short code
const square = n => n * n;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
❌ Forgetting to call a function
function greet() { console.log("Hi!"); }
greet; // ❌ Does nothing
greet(); // ✅ Calls the functionfunction add(a, b) { a + b; } // ❌function add(a, b) { return a + b; }❌ 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
function toFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
console.log(toFahrenheit(0)); // 322️⃣ A function that checks if a number is even
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(10)); // true3️⃣ An arrow function that finds the maximum of two numbers
const max = (a, b) => (a > b ? a : b);
console.log(max(5, 10)); // 104️⃣ A function with default parameters that creates a greeting message
function greet(name = "Guest") {
return `Hello, ${name}! Welcome back!`;
}
console.log(greet());
console.log(greet("Brayan"));💬 Recap
- ✅ Functions let you group reusable logic
- ✅ Parameters allow input flexibility
- ✅ return gives you reusable results
- ✅ Arrow functions make syntax modern and shorter
- ✅ Default parameters make your functions safer
💡 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
| Concept | Syntax |
|---|---|
| Declaration | function greet(name) { ... } |
| Arrow function | const greet = (name) => { ... } |
| Return value | return a + b; |
| Default param | function greet(name = "Guest") |
| Short arrow | const double = x => x * 2; |
Lesson Complete — JavaScript Functions!
You can now write reusable code with parameters, return values, arrow functions, and default arguments.
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
- Previous: Variables and Data Types
- Next: Strings & String Methods — slice, split, replace, template literals and the string methods you'll use daily
- Quick reference: JavaScript cheat sheet › Functions