Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Functions, Parameters, Return Values and Scope

Learn how JavaScript functions work, how to define and call functions, use parameters and arguments, return values, default parameters, arrow functions and understand variable scope.

🎯

Learning Objectives

["Understand what JavaScript functions are and why they are important.","Define and call JavaScript functions.","Use function parameters and arguments correctly.","Understand the difference between parameters and arguments.","Return values from functions using the return statement.","Use default parameters when arguments are not provided.","Understand local and global scope.","Understand block scope with let and const.","Understand function scope and lexical scope.","Write reusable functions that perform focused tasks.","Use function expressions and arrow functions.","Understand when a function should return a value instead of only producing output.","Apply functions to practical web development problems."]

📖

Lesson Content

Introduction

As JavaScript programs become larger, writing every instruction directly in one long block of code becomes difficult to manage.

Functions solve this problem by allowing developers to group reusable instructions into named blocks of code.

A function can receive data, process that data, and optionally return a result.

Functions are one of the most important concepts in JavaScript because they help developers create code that is:

  • Reusable
  • Organized
  • Readable
  • Maintainable
  • Easier to test

In this lesson, you will learn how to create and use functions, pass information into functions, return results, and understand how variable scope affects functions.


1. What Is a Function?

A function is a reusable block of code designed to perform a particular task.

For example, instead of writing a greeting repeatedly:

console.log("Welcome to Dwallnet Technologies.");
console.log("Welcome to Dwallnet Technologies.");
console.log("Welcome to Dwallnet Technologies.");

You can create a function:

function greet() {
    console.log("Welcome to Dwallnet Technologies.");
}

The function can then be called whenever it is needed:

greet();
greet();
greet();

The function definition describes what the function does, while calling the function tells JavaScript to execute it.


2. Defining a Function

The basic syntax for a function declaration is:

function functionName() {
    // Instructions
}

Example:

function sayHello() {
    console.log("Hello, JavaScript!");
}

The function has three important parts:

  • function — tells JavaScript that a function is being declared.
  • sayHello — the function name.
  • () — contains parameters when the function needs input.

3. Calling a Function

Defining a function does not automatically execute it.

You must call it:

sayHello();

The parentheses tell JavaScript to execute the function.

Example:

function displayMessage() {
    console.log("Learning JavaScript at Dwallnet.");
}

displayMessage();

4. Functions with Parameters

A function can receive information through parameters.

function greetStudent(name) {
    console.log(`Welcome, ${name}!`);
}

greetStudent("Ade");
greetStudent("Mary");

Here, name is a parameter.

The function can receive different values each time it is called.


5. Parameters versus Arguments

These two terms are related but describe different things.

A parameter is the variable listed in the function definition.

function greetStudent(name) {
    console.log(name);
}

name is the parameter.

An argument is the actual value passed when the function is called.

greetStudent("Ade");

"Ade" is the argument.


6. Multiple Parameters

A function can accept more than one parameter.

function addNumbers(firstNumber, secondNumber) {
    console.log(firstNumber + secondNumber);
}

addNumbers(10, 5);

The function receives two values and adds them together.

Another example:

function introduceStudent(name, course) {
    console.log(
        `${name} is learning ${course}.`
    );
}

introduceStudent(
    "Ade",
    "Web Development"
);

7. Return Values

Functions can send a result back to the code that called them using the return statement.

function addNumbers(a, b) {
    return a + b;
}

const result = addNumbers(10, 5);

console.log(result);

The function calculates the result and returns it.

The returned value can then be stored in a variable, displayed, passed to another function, or used in another calculation.


8. return Stops Function Execution

When JavaScript reaches a return statement, the function immediately stops executing.

function checkNumber(number) {
    if (number > 10) {
        return "Number is greater than 10";
    }

    return "Number is 10 or less";
}

Once the first return is reached, the function does not continue executing statements after it in that execution path.


9. Functions Without return

Not every function needs to return a value.

function showMessage() {
    console.log("Welcome to the student dashboard.");
}

showMessage();

This function performs an action but does not explicitly return a result.

When a JavaScript function does not return a value explicitly, its return value is undefined.


10. Reusable Functions

One major advantage of functions is code reuse.

function calculateArea(length, width) {
    return length * width;
}

const areaOne = calculateArea(10, 5);
const areaTwo = calculateArea(20, 8);

console.log(areaOne);
console.log(areaTwo);

The same function can handle different inputs without duplicating the calculation logic.


11. Default Parameters

A function can provide a default value for a parameter.

function greet(name = "Student") {
    console.log(`Welcome, ${name}!`);
}

greet("Ade");
greet();

The first call uses "Ade".

The second call uses the default value "Student" because no argument was supplied for name.


12. Functions and Multiple Return Values

A function can directly return one value, but that value can be an object or array containing multiple pieces of information.

Example:

function getStudent() {
    return {
        name: "Ade",
        course: "Web Development",
        score: 85
    };
}

const student = getStudent();

console.log(student.name);
console.log(student.course);
console.log(student.score);

This is useful when a function needs to produce several related values.


13. Function Expressions

A function can also be stored in a variable. This is called a function expression.

const greet = function(name) {
    console.log(`Hello, ${name}!`);
};

greet("Ade");

Functions in JavaScript are values, which means they can be stored in variables, passed to other functions, and returned from functions.


14. Arrow Functions

Modern JavaScript provides a shorter function syntax called an arrow function.

Traditional function:

function add(a, b) {
    return a + b;
}

Arrow function:

const add = (a, b) => {
    return a + b;
};

For a simple expression, the arrow function can be shortened further:

const add = (a, b) => a + b;

Arrow functions are widely used in modern JavaScript, especially with arrays, callbacks and asynchronous programming.


15. Arrow Functions with One Parameter

When an arrow function has exactly one parameter, the parentheses can be omitted.

const double = number => number * 2;

console.log(double(5));

However, keeping parentheses can sometimes improve consistency and readability:

const double = (number) => number * 2;

Both forms are valid.


16. Function Scope

Variables declared inside a function using let or const are generally local to that function.

function showStudent() {
    const studentName = "Ade";

    console.log(studentName);
}

showStudent();

The variable studentName exists inside the function’s scope.

Trying to access it outside the function will not work because it is not available in the outer scope.


17. Global Scope

A variable declared outside functions can be available in a wider scope.

const academyName = "Dwallnet Technologies";

function showAcademy() {
    console.log(academyName);
}

showAcademy();

The function can access academyName because the variable was declared in an outer scope.

Although global variables can be useful, avoid creating unnecessary global state because too many global variables can make applications difficult to maintain.


18. Block Scope

Variables declared with let and const are block-scoped.

if (true) {
    const message = "Inside the block";

    console.log(message);
}

The variable belongs to the block created by the braces.

This also applies to loops:

for (let i = 0; i < 3; i++) {
    console.log(i);
}

The variable i is scoped to the loop.


19. Scope and Nested Functions

Functions can be nested inside other functions.

function outerFunction() {
    const academy = "Dwallnet";

    function innerFunction() {
        console.log(academy);
    }

    innerFunction();
}

outerFunction();

The inner function can access variables from its surrounding scope.

This behavior is related to JavaScript’s lexical scope.


20. Lexical Scope

Lexical scope means that the accessibility of variables is determined by where functions and blocks are written in the source code.

Example:

const academy = "Dwallnet";

function outer() {
    const course = "Web Development";

    function inner() {
        console.log(academy);
        console.log(course);
    }

    inner();
}

outer();

The inner function can access variables from its own scope and surrounding outer scopes.


21. Function Parameters and Validation

Functions can validate their inputs before processing them.

function calculateDiscount(price, discount) {
    if (price < 0 || discount < 0) {
        return 0;
    }

    return price - (price * discount / 100);
}

console.log(
    calculateDiscount(10000, 10)
);

This makes the function more reliable because it checks whether the supplied values are sensible before performing the calculation.


22. Functions with Conditional Statements

Functions and conditional statements work together frequently.

function getGrade(score) {
    if (score >= 70) {
        return "A";
    } else if (score >= 60) {
        return "B";
    } else if (score >= 50) {
        return "C";
    } else if (score >= 40) {
        return "D";
    }

    return "F";
}

console.log(getGrade(82));

This function can be reused for any score.


23. Functions with Loops

Functions can also contain loops.

function printCourses(courses) {
    for (const course of courses) {
        console.log(course);
    }
}

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

printCourses(courses);

This creates a reusable function for displaying course names.


24. Passing Arrays to Functions

Arrays can be passed to functions as arguments.

function countStudents(students) {
    return students.length;
}

const students = [
    "Ade",
    "Mary",
    "John",
    "David"
];

console.log(
    countStudents(students)
);

This is common when working with data returned from an API or database.


25. Passing Objects to Functions

Objects can also be passed into functions.

function displayStudent(student) {
    console.log(
        `${student.name} is studying ${student.course}.`
    );
}

const student = {
    name: "Ade",
    course: "Web Development"
};

displayStudent(student);

This approach is useful when working with structured application data.


26. Function Composition

One function can call another function.

function calculateTotal(price, quantity) {
    return price * quantity;
}

function displayTotal(price, quantity) {
    const total = calculateTotal(price, quantity);

    console.log(`Total: ${total}`);
}

displayTotal(2500, 3);

Breaking a large operation into smaller functions can make an application easier to understand and maintain.


27. Pure Functions

A pure function produces the same output when given the same input and does not modify external state.

function multiply(a, b) {
    return a * b;
}

console.log(multiply(4, 5));
console.log(multiply(4, 5));

Both calls produce the same result because the function depends only on its parameters.

Pure functions are often easier to test and reason about.


28. Functions That Modify External Data

Not every function is pure.

let totalStudents = 0;

function addStudent() {
    totalStudents++;
}

addStudent();

console.log(totalStudents);

This function changes a variable outside its own local scope.

Changing external state is sometimes necessary in applications, but it should be done deliberately because it can make code harder to reason about.


29. Callback Functions

Because functions are values in JavaScript, one function can be passed to another function as an argument.

function processStudent(name, callback) {
    console.log(`Processing ${name}...`);
    callback();
}

function completed() {
    console.log("Processing completed.");
}

processStudent("Ade", completed);

The function passed as an argument is called a callback function.

Callbacks are an important part of JavaScript and will become especially useful when working with array methods, events and asynchronous operations.


30. Anonymous Functions

A function without a name is called an anonymous function.

const greet = function() {
    console.log("Hello!");
};

greet();

Anonymous functions are frequently used when a function is needed temporarily, such as a callback.


31. Function Hoisting

Function declarations can be called before their declaration in the source code because function declarations are hoisted.

sayHello();

function sayHello() {
    console.log("Hello!");
}

This works with a function declaration.

However, function expressions stored in variables do not behave the same way:

greet();

const greet = function() {
    console.log("Hello!");
};

This should not be relied upon because the variable is not initialized before the call.

For clarity, many developers prefer declaring functions before using them.


32. Rest Parameters

A function can accept an indefinite number of arguments using a rest parameter.

function addAll(...numbers) {
    let total = 0;

    for (const number of numbers) {
        total += number;
    }

    return total;
}

console.log(addAll(10, 20));
console.log(addAll(10, 20, 30, 40));

The ...numbers syntax collects the supplied arguments into an array.


33. Returning Boolean Values

Functions are often used to answer yes-or-no questions.

function isAdult(age) {
    return age >= 18;
}

console.log(isAdult(20));
console.log(isAdult(15));

The function returns either true or false.

This type of function can be used directly in conditional statements:

if (isAdult(20)) {
    console.log("Access allowed.");
}

34. Functions and Web Forms

Functions are frequently used when processing form input.

function validateEmail(email) {
    if (!email.includes("@")) {
        return false;
    }

    return true;
}

const email = "student@example.com";

if (validateEmail(email)) {
    console.log("Email is valid.");
} else {
    console.log("Please enter a valid email.");
}

In later lessons, this type of logic can be connected to real HTML forms and DOM events.


35. Good Function Design

A good function should generally have a clear responsibility.

Instead of creating one huge function that performs many unrelated tasks, divide the work into smaller functions.

For example:

function validateStudent(student) {
    // Validate data
}

function calculateStudentResult(student) {
    // Calculate result
}

function displayStudentResult(student) {
    // Display result
}

Each function has a focused responsibility.


36. Function Naming

Function names should clearly describe what the function does.

Good examples:

calculateTotal();
validateEmail();
getStudent();
displayCourse();
saveRegistration();

Less descriptive names make code harder to understand:

doThing();
process();
run();
x();

Clear names improve readability and make projects easier to maintain.


37. Avoid Functions That Do Too Much

A function that performs many unrelated operations can become difficult to test and maintain.

Instead of:

function processEverything() {
    // Validate form
    // Save student
    // Calculate score
    // Send notification
    // Update dashboard
}

Consider separating responsibilities:

function validateForm() {
    // Validation
}

function saveStudent() {
    // Saving
}

function calculateScore() {
    // Calculation
}

function updateDashboard() {
    // Dashboard update
}

38. Practical Project: Student Result Calculator

Let’s combine several concepts from this lesson.

function calculateAverage(scores) {
    let total = 0;

    for (const score of scores) {
        total += score;
    }

    return total / scores.length;
}

function getGrade(score) {
    if (score >= 70) {
        return "A";
    }

    if (score >= 60) {
        return "B";
    }

    if (score >= 50) {
        return "C";
    }

    if (score >= 40) {
        return "D";
    }

    return "F";
}

function displayResult(studentName, scores) {
    const average = calculateAverage(scores);
    const grade = getGrade(average);

    console.log(`Student: ${studentName}`);
    console.log(`Average: ${average}`);
    console.log(`Grade: ${grade}`);
}

displayResult(
    "Ade",
    [75, 80, 70, 85]
);

This example demonstrates:

  • Functions
  • Parameters
  • Arguments
  • Return values
  • Arrays
  • Loops
  • Conditional statements
  • Function composition

39. Functions in Modern Web Applications

Functions are everywhere in modern JavaScript applications.

They are used to:

  • Validate forms.
  • Calculate values.
  • Process user input.
  • Generate HTML content.
  • Handle button clicks.
  • Communicate with APIs.
  • Process server responses.
  • Manage application state.
  • Filter and transform data.
  • Perform asynchronous operations.

Learning functions properly prepares you for DOM programming, events, APIs, asynchronous JavaScript and larger application architecture.


40. Best Practices for JavaScript Functions

  • Give functions meaningful names.
  • Keep functions focused on a clear responsibility.
  • Use parameters to make functions reusable.
  • Return values when the calling code needs a result.
  • Validate important inputs.
  • Avoid unnecessary global variables.
  • Prefer const for function references that will not be reassigned.
  • Use arrow functions when their shorter syntax improves readability.
  • Keep complicated functions broken into smaller logical units.
  • Write functions that are easy to test independently.

Lesson Summary

Functions are reusable blocks of JavaScript code designed to perform specific tasks. They can receive information through parameters and arguments and can send results back through the return statement.

JavaScript supports function declarations, function expressions and arrow functions. Functions can also work with arrays, objects, loops, conditional statements and other functions.

Understanding scope is equally important. Variables can exist in global, function or block scopes, and nested functions can access variables from surrounding scopes through lexical scope.

Well-designed functions make JavaScript applications easier to read, reuse, test and maintain.


Practice Exercise

  1. Create a function called greetStudent that accepts a student’s name and displays a greeting.
  2. Create a function called addNumbers that accepts two numbers and returns their sum.
  3. Create a function that calculates the area of a rectangle.
  4. Create a function that accepts a student’s score and returns a grade.
  5. Create a function that receives an array of course names and displays each course.
  6. Create an arrow function that doubles a number.
  7. Create a function with a default parameter.
  8. Create a function that returns true when a number is even.
  9. Create a function that accepts a student object and returns the student’s course.
  10. Create a mini student result calculator using at least three separate functions.
💻

Code Example

function calculateAverage(scores) {
    if (scores.length === 0) {
        return 0;
    }

    let total = 0;

    for (const score of scores) {
        total += score;
    }

    return total / scores.length;
}

function getGrade(score) {
    if (score >= 70) {
        return "A";
    }

    if (score >= 60) {
        return "B";
    }

    if (score >= 50) {
        return "C";
    }

    if (score >= 40) {
        return "D";
    }

    return "F";
}

function createStudent(name = "Student", course = "Web Development") {
    return {
        name,
        course
    };
}

const student = createStudent("Ade");

const scores = [75, 80, 70, 85];

const average = calculateAverage(scores);
const grade = getGrade(average);

console.log(`Student: ${student.name}`);
console.log(`Course: ${student.course}`);
console.log(`Average: ${average}`);
console.log(`Grade: ${grade}`);

// Arrow function
const isPassed = (score) => score >= 40;

console.log(isPassed(65));

// Rest parameter
function addAll(...numbers) {
    return numbers.reduce(
        (total, number) => total + number,
        0
    );
}

console.log(addAll(10, 20, 30, 40));
⭐

Key Takeaways

["Functions are reusable blocks of code designed to perform specific tasks.","A function must be called before its instructions execute.","Parameters define the inputs a function expects.","Arguments are the actual values passed to a function.","The return statement sends a value back to the calling code.","A function can return numbers, strings, booleans, arrays, objects or other values.","Default parameters provide fallback values when arguments are not supplied.","Function expressions store functions in variables.","Arrow functions provide concise modern JavaScript syntax.","Variables declared inside functions are generally local to that function.","let and const are block-scoped.","Lexical scope allows nested functions to access variables from surrounding scopes.","Functions can receive arrays and objects as arguments.","Functions can call other functions to divide complex work into smaller tasks.","Pure functions are predictable because their results depend on their inputs.","Callbacks allow functions to be passed to other functions.","Meaningful function names and focused responsibilities improve code maintainability."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress