Skip to main content
JavaScript Basics
CHAPTER 08 Beginner

JavaScript Functions

Updated: May 12, 2026
25 min read

# JavaScript Functions

Imagine you have a recipe for baking a cake. Instead of writing out the entire recipe every single time someone asks how to bake one, you write it on a recipe card, name it "Chocolate Cake", and simply hand them the card when they need it.

In JavaScript, Functions are those recipe cards. They are blocks of reusable code designed to perform a particular task.

1. Introduction

A JavaScript function is executed when "something" invokes it (calls it). Functions are the building blocks of readable, maintainable, and professional code. They prevent you from duplicating code (the "DRY" principle - Don't Repeat Yourself).

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Declare and call a function.
  • Pass data into functions using parameters and arguments.
  • Return data back out of a function using the return keyword.
  • Understand function expressions and anonymous functions.
  • Build a working BMI (Body Mass Index) Calculator project.

3. Function Declarations

To create a function, you use the function keyword, followed by a name, parentheses (), and curly braces {}.

javascript
1234
// Syntax
function nameOfFunction() {
    // code to be executed
}

To make the function actually run, you must "call" or "invoke" it by writing its name followed by parentheses.

javascript
12
// Calling the function
nameOfFunction();

4. Parameters and Arguments

Functions become powerful when you can pass data into them. The variables listed inside the parentheses in the function definition are called Parameters. The actual values you pass to the function when you call it are called Arguments.

javascript
123456
// Syntax
function greetUser(firstName) { // firstName is a parameter
    console.log("Hello " + firstName);
}

greetUser("Alice"); // "Alice" is the argument

5. The return Statement

Sometimes, a function is meant to calculate something and give the result back to you, rather than just printing it to the console or DOM. When JavaScript reaches a return statement, the function stops executing and sends the value back to where it was called.

javascript
123456
// Syntax
function add(a, b) {
    return a + b;
}

let result = add(5, 10); // result is now 15

---

6. Real-world Examples & Code Snippets

Example 1: Basic Function

javascript
1234567
// Example JavaScript
function sayHello() {
    console.log("Hello, World!");
}

sayHello(); // Executes the function
sayHello(); // Executes it again

Example 2: Function with Multiple Parameters

javascript
12345678
// Example JavaScript
function calculateTotal(price, taxRate) {
    let total = price + (price * taxRate);
    console.log("Total is: $" + total);
}

calculateTotal(100, 0.05); // Output: Total is: $105
calculateTotal(50, 0.10);  // Output: Total is: $55

Example 3: Function with a Return Value

javascript
1234567
// Example JavaScript
function getSquare(number) {
    return number * number;
}

let mySquare = getSquare(4);
console.log(mySquare); // Output: 16

Output Explanation: The function calculates 4 * 4 and returns 16. That 16 is then saved into the mySquare variable.

Example 4: The Code AFTER Return Never Runs

javascript
12345
// Example JavaScript
function testReturn() {
    return "This is returned";
    console.log("This will NEVER be printed"); // Unreachable code
}

Example 5: Default Parameters (ES6)

You can provide default values in case the user forgets to pass an argument.

javascript
1234567
// Example JavaScript
function greet(name = "Guest") {
    console.log("Welcome, " + name);
}

greet("John"); // Output: Welcome, John
greet();       // Output: Welcome, Guest

Example 6: Anonymous Functions

A function without a name is an anonymous function. It is often used when a function is passed as an argument to another function, or tied to an event listener.

javascript
123456789
// Example JavaScript
let btn = document.getElementById("myBtn");

// We don't name this function, it just exists for this click event
/*
btn.onclick = function() {
    console.log("Button clicked!");
};
*/

Example 7: Function Expressions

You can store a function inside a variable. This is called a function expression.

javascript
123456
// Example JavaScript
const multiply = function(x, y) {
    return x * y;
};

console.log(multiply(5, 3)); // Output: 15

Example 8: Functions Calling Functions

Functions can call other functions. This is how complex programs are built.

javascript
1234567891011
// Example JavaScript
function formatPrice(amount) {
    return "$" + amount.toFixed(2);
}

function printReceipt(itemName, price) {
    let formatted = formatPrice(price);
    console.log("Item: " + itemName + " | Cost: " + formatted);
}

printReceipt("Coffee", 3.5); // Output: Item: Coffee | Cost: $3.50

Example 9: Variable Scope Basics in Functions

Variables created inside a function CANNOT be accessed outside of it. (We will cover this deeply in the next chapter).

javascript
12345
// Example JavaScript
function secretVault() {
    let secretCode = "12345";
}
// console.log(secretCode); // ERROR: secretCode is not defined

Example 10: Formatting a Username

A practical function that cleans up dirty user input.

javascript
123456789
// Example JavaScript
function cleanUsername(rawName) {
    let trimmedName = rawName.trim(); // Removes extra spaces
    let cleanName = trimmedName.toLowerCase();
    return cleanName;
}

let rawInput = "   SUPER_USER_99   ";
console.log(cleanUsername(rawInput)); // Output: "super_user_99"

---

7. Common Mistakes for Beginners

  1. 1. Forgetting to invoke the function: Writing function sayHi() { ... } but never writing sayHi(); below it. The code inside will never run.
  1. 2. Confusing Return with Console.log: console.log() just prints text for the developer to see. return actually passes data back to the program so other variables can use it. They are entirely different things.
  1. 3. Passing arguments in the wrong order: If you have function divide(a, b) and you call divide(2, 10), a becomes 2 and b becomes 10. Order matters strictly.

8. Best Practices

  • One function, one task: A function should do exactly one thing. If your function is named calculateTax, it should not also be updating the HTML layout and sending an email.
  • Use descriptive names: Names like doStuff() or func1() are terrible. Use verb-noun pairings like calculateTotal(), getUserData(), or validateEmail().
  • Keep them small: If your function is 200 lines long, it should probably be broken down into smaller helper functions.

9. Mini Project: BMI Calculator

Let's build a functional Body Mass Index (BMI) calculator.

HTML:

html
1234567891011121314151617181920212223242526272829
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        .app-box { font-family: Arial; padding: 20px; border: 1px solid #ccc; width: 300px; border-radius: 10px; background: #fff;}
        input { display: block; margin-bottom: 10px; padding: 8px; width: 90%; }
        button { padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;}
        #bmiResult { font-size: 20px; margin-top: 15px; font-weight: bold;}
    </style>
</head>
<body>

    <div class="app-box">
        <h2>BMI Calculator</h2>
        <label>Weight (kg):</label>
        <input type="number" id="weight" value="70">
        
        <label>Height (meters):</label>
        <input type="number" id="height" value="1.75">
        
        <button onclick="handleCalculate()">Calculate BMI</button>
        <div id="bmiResult"></div>
    </div>

    <script src="bmi.js"></script>
</body>
</html>

bmi.js:

javascript
12345678910111213141516171819202122232425262728
// Example JavaScript

// Helper function to do the pure math
function calculateBMI(weight, height) {
    return weight / (height * height);
}

// Helper function to determine the category
function getBMICategory(bmiScore) {
    if (bmiScore < 18.5) return "Underweight";
    if (bmiScore < 24.9) return "Normal Weight";
    if (bmiScore < 29.9) return "Overweight";
    return "Obese";
}

// Main handler function connected to the HTML button
function handleCalculate() {
    let w = Number(document.getElementById("weight").value);
    let h = Number(document.getElementById("height").value);
    
    // Call our helper functions
    let bmi = calculateBMI(w, h);
    let category = getBMICategory(bmi);
    
    // Output to screen (using toFixed to round to 1 decimal place)
    document.getElementById("bmiResult").innerHTML = 
        "BMI: " + bmi.toFixed(1) + " (" + category + ")";
}

How it works: We separated our concerns! One function handles math, one handles text categorization, and the main handler grabs the DOM elements and orchestrates the other functions. This is professional architecture!

10. Exercises

  1. 1. Write a function called multiplyByTen that takes one parameter, multiplies it by 10, and returns the result.
  1. 2. Call the function you just made, passing the number 5, and console.log() the returned result.
  1. 3. Write a function called checkEven that takes a number, and returns true if it is even, and false if it is odd. (Hint: Use the modulus % operator).

11. MCQs (Multiple Choice Questions)

Q1: What keyword is used to send a value back out of a function? A) output B) send C) return D) export *Answer: C*

Q2: What are the variables listed inside the parentheses of a function definition called? A) Arguments B) Parameters C) Arrays D) Pointers *Answer: B*

Q3: Which of the following correctly calls a function named myFunction? A) call myFunction() B) myFunction; C) execute myFunction() D) myFunction() *Answer: D*

12. Interview Questions

Q: What is the difference between a Parameter and an Argument? *A: A parameter is the variable declared in the function definition (the placeholder). An argument is the actual data value passed into the function when it is called/invoked.*

Q: What happens if a function does not have a return statement, but you try to save its result to a variable? *A: The function will execute normally, but the variable will be assigned the value undefined, because a function that does not explicitly return a value implicitly returns undefined.*

13. FAQs

Q: Can a function return multiple values? *A: A function can only return one single thing. However, that "thing" can be an Array or an Object that contains multiple pieces of data. (We will learn this in Chapters 10 and 11).*

14. Summary

  • Functions package code into reusable blocks.
  • You declare a function once, and can call it infinite times.
  • Parameters let you pass data into functions.
  • The return keyword stops the function and outputs a value.
  • Breaking large programs into small, single-task helper functions is a best practice.

15. Next Chapter Recommendation

In this chapter, we saw a glimpse of a variable disappearing outside of a function. The rules of where variables live and die are called Scope. In the next chapter, JavaScript Scope and Hoisting, we will uncover the invisible rules that govern every variable you create.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·