JavaScript Functions: Parameters, Return Values and Arrow Functions

JavaScript functions let you group code into reusable blocks.

A shopping website can use a function to calculate a cart total. A form can use a function to check an email address. A button can call a function when somebody clicks it.

Instead of writing the same code again and again, you can place that logic inside a function and run it whenever you need it.

Course Home: JavaScript Tutorial for Beginners
Previous Lesson: JavaScript Loops Explained
Next Lesson: JavaScript Arrays Explained for Beginners

Quick Answer

A JavaScript function is a reusable block of code.

A simple function looks like this:

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

The function does not run until you call it:

greet();

Output:

Hello

Functions can also receive values:

function greet(name) {
    console.log(`Hello ${name}`);
}

greet("Riya");

Output:

Hello Riya

And they can return a result:

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

const total = add(5, 3);

console.log(total);

Output:

8

What Is a Function in JavaScript?

A function is a named or stored block of code that performs a task.

For example:

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

This creates a function called:

showMessage

The code inside the braces belongs to that function.

To run it:

showMessage();

Output:

Welcome to the website

Creating a function and running a function are two different steps.

Why JavaScript Functions Matter

Functions help you:

  • Reuse code
  • Avoid repeating the same logic
  • Break large programs into smaller parts
  • Give meaningful names to tasks
  • Pass different values into the same logic
  • Return calculated results
  • Organize event handling
  • Work with arrays and objects
  • Keep website code easier to maintain

Without functions, repeated tasks can quickly make your code longer and harder to change.

Function Declaration Syntax

A basic function declaration looks like this:

function functionName() {
    // code
}

Example:

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

Here:

  • function is the keyword.
  • sayHello is the function name.
  • () holds parameters when needed.
  • {} contains the function body.

The function runs only when you call it.

sayHello();

Function Declaration vs Function Call

This creates the function:

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

This calls the function:

greet();

A common beginner mistake is creating a function but never calling it.

For example:

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

This produces no output by itself.

You must call:

greet();

Calling a Function More Than Once

A major benefit of functions is reuse.

function showWelcome() {
    console.log("Welcome");
}

showWelcome();
showWelcome();
showWelcome();

Output:

Welcome
Welcome
Welcome

You write the function logic once and call it whenever needed.

Real Website Example: Show a Notification

Suppose a website needs the same message in several places.

function showSuccessMessage() {
    console.log("Saved successfully");
}

You can call it after different actions:

showSuccessMessage();

Instead of repeating:

console.log("Saved successfully");

throughout the project, one function keeps the logic in one place.

What Are Function Parameters?

Parameters are names listed inside a function definition.

They let a function receive information.

Example:

function greet(name) {
    console.log(`Hello ${name}`);
}

Here:

name

is a parameter.

You can call the function with:

greet("Amit");

Output:

Hello Amit

The value "Amit" is passed into the parameter name.

What Are Function Arguments?

An argument is the actual value passed when you call a function.

Example:

function greet(name) {
    console.log(`Hello ${name}`);
}

greet("Riya");

Here:

name

is the parameter.

And:

"Riya"

is the argument.

A simple way to remember it:

  • Parameter → name in the function definition
  • Argument → value passed during the function call

Functions With Multiple Parameters

A function can accept more than one parameter.

Example:

function add(a, b) {
    console.log(a + b);
}

Call it:

add(5, 3);

Output:

8

Another example:

function showProduct(name, price) {
    console.log(`${name} costs ₹${price}`);
}

showProduct("Keyboard", 1500);

Output:

Keyboard costs ₹1500

The arguments are matched to the parameters by position.

Argument Order Matters

Consider:

function showUser(name, city) {
    console.log(`${name} lives in ${city}`);
}

Correct:

showUser("Riya", "Delhi");

Output:

Riya lives in Delhi

If you reverse the arguments:

showUser("Delhi", "Riya");

Output:

Delhi lives in Riya

JavaScript does not know what each value means. It only follows the position.

Real Website Example: Calculate Product Total

A reusable pricing function can accept a price and quantity.

function calculateTotal(price, quantity) {
    console.log(price * quantity);
}

Call it:

calculateTotal(500, 3);

Output:

1500

Use it again:

calculateTotal(1200, 2);

Output:

2400

The same function handles different values.

What Does return Do in JavaScript?

The return statement sends a value back from a function.

Example:

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

Call the function:

const result = add(5, 3);

Now:

console.log(result);

Output:

8

Instead of printing the result inside the function, return gives the result back to the code that called it.

console.log vs return

These are not the same.

Using console.log

function add(a, b) {
    console.log(a + b);
}

This prints the result.

But:

const result = add(5, 3);

does not store 8 in result.

The function did not return it.

Using return

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

const result = add(5, 3);

console.log(result);

Output:

8

Use return when another part of your program needs the result.

Code After return Does Not Run

Consider:

function test() {
    return "Done";

    console.log("Hello");
}

The console.log() is never reached.

Once JavaScript reaches return, the function stops.

This can be useful for ending a function early.

Real Website Example: Calculate Discount

Suppose you want a reusable discount function.

function calculateDiscount(price, percent) {
    return price * percent / 100;
}

Call it:

const discount = calculateDiscount(2000, 10);

console.log(discount);

Output:

200

Then calculate the final price:

const finalPrice = 2000 - discount;

console.log(finalPrice);

Output:

1800

This is a practical example of one function returning a value that other code can use.

Functions Can Return Booleans

A function can return true or false.

Example:

function hasStock(stock) {
    return stock > 0;
}

Call:

console.log(hasStock(5));

Output:

true

Another call:

console.log(hasStock(0));

Output:

false

You can use the returned boolean inside a condition:

if (hasStock(3)) {
    console.log("Product available");
}

This combines JavaScript functions with JavaScript if else.

Functions Can Return Strings

Example:

function getStockMessage(stock) {
    if (stock > 0) {
        return "In stock";
    }

    return "Out of stock";
}

Call:

const message = getStockMessage(5);

console.log(message);

Output:

In stock

Functions Can Return Objects

A function can return more complex values.

Example:

function createProduct(name, price) {
    return {
        name: name,
        price: price
    };
}

Call:

const product = createProduct("Laptop", 50000);

console.log(product);

This returns an object containing the product details.

You will learn objects properly in the JavaScript Objects tutorial.

Default Parameters

A parameter can have a default value.

Example:

function greet(name = "Guest") {
    console.log(`Hello ${name}`);
}

Call without an argument:

greet();

Output:

Hello Guest

Call with an argument:

greet("Riya");

Output:

Hello Riya

The provided argument replaces the default value.

Real Website Example: Default Shipping Cost

function calculateTotal(price, shipping = 100) {
    return price + shipping;
}

Call:

console.log(calculateTotal(1000));

Output:

1100

Or provide another shipping value:

console.log(calculateTotal(1000, 50));

Output:

1050

Missing Arguments

Consider:

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

Call:

console.log(add(5));

The missing parameter b becomes:

undefined

The calculation:

5 + undefined

produces:

NaN

Use required arguments correctly or provide sensible default parameters where they make sense.

Extra Arguments

JavaScript allows extra arguments.

Example:

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

greet("Amit", "Delhi");

Output:

Amit

The second argument is not used because the function only refers to the first parameter.

For clear beginner code, pass only the values your function expects.

Function Scope

Variables declared inside a function are normally available only inside that function.

Example:

function showUser() {
    const userName = "Riya";

    console.log(userName);
}

Inside the function, this works.

But outside:

console.log(userName);

causes an error because userName is not available there.

This is called function scope.

Local Variables

A variable created inside a function is often called a local variable.

Example:

function calculateTotal() {
    const price = 500;
    const quantity = 2;
    const total = price * quantity;

    console.log(total);
}

The variables belong to that function’s work.

Keeping temporary values local helps prevent them from affecting unrelated code.

Functions Can Read Outer Variables

Consider:

const taxRate = 0.18;

function calculateTax(price) {
    return price * taxRate;
}

The function can read:

taxRate

because it exists in an outer scope.

Call:

console.log(calculateTax(1000));

Output:

180

You will study scope more deeply later.

Avoid Changing Global Variables Without Need

Consider:

let total = 0;

function addPrice(price) {
    total += price;
}

This changes an outer variable.

Sometimes that is intentional, but it can make code harder to understand.

When possible, prefer returning a value:

function addPrice(total, price) {
    return total + price;
}

This makes the function’s result easier to follow.

Function Naming Best Practices

Function names should describe actions.

Good examples:

calculateTotal()
showMessage()
validateEmail()
getUserName()
checkStock()
createProduct()

Less useful:

doThing()
runIt()
x()
abc()

A clear function name tells you what the function does before you read its body.

Use Verb-Based Function Names

Functions usually perform actions.

Names often start with verbs such as:

get
set
show
hide
check
validate
calculate
create
remove
update
format
find

Examples:

function calculatePrice() {
    // ...
}
function validateForm() {
    // ...
}
function showMenu() {
    // ...
}

Keep Functions Focused

A function is easier to understand when it has one clear job.

Instead of one function that:

  • validates a form
  • calculates a price
  • updates the page
  • sends data

consider smaller functions for each task.

For example:

function validateEmail(email) {
    return email !== "";
}
function calculateTotal(price, quantity) {
    return price * quantity;
}

Small focused functions are easier to test and reuse.

Function Expressions

A function can also be stored in a variable.

Example:

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

Call it:

greet();

Output:

Hello

This is called a function expression.

Function Declaration vs Function Expression

Function declaration:

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

Function expression:

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

Both can be called with:

greet();

One important difference is how they behave before the line where they are defined.

Function Declaration Hoisting

A function declaration can usually be called before its declaration appears in the source code.

Example:

greet();

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

Output:

Hello

JavaScript makes the function declaration available during code setup.

Function Expression Before Declaration

This does not work:

greet();

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

The const variable cannot be used before its declaration is initialized.

For beginner code, a simple rule is:

Define functions before the code that uses them when that makes the file easier to read.

You do not need to depend on hoisting.

JavaScript Arrow Functions

Arrow functions provide a shorter function syntax.

Traditional function expression:

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

Arrow function:

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

Call it the same way:

greet();

Output:

Hello

Arrow Function With Parameters

Example:

const greet = (name) => {
    console.log(`Hello ${name}`);
};

Call:

greet("Riya");

Output:

Hello Riya

With one simple parameter, parentheses can be omitted:

const greet = name => {
    console.log(`Hello ${name}`);
};

For beginners, keeping the parentheses can make the structure easier to recognize.

Arrow Function With Multiple Parameters

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

Call:

console.log(add(5, 3));

Output:

8

Short Arrow Function Return

When an arrow function contains only one returned expression, it can be shortened.

Longer version:

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

Shorter version:

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

Call:

console.log(add(5, 3));

Output:

8

The returned value is implicit.

When Arrow Functions Are Useful

Arrow functions are common in modern JavaScript, especially with:

  • Array methods
  • Event callbacks
  • Promise callbacks
  • Small helper functions
  • Modern frontend frameworks

You will see them often in later lessons.

For example:

const prices = [500, 1000, 1500];

const doubled = prices.map((price) => price * 2);

Do not worry about map() yet.

You will learn array methods after the basic arrays lesson.

Arrow Functions Are Not Always the Same as Normal Functions

Arrow functions handle this differently from regular functions.

They also cannot be used as constructors with new.

These differences matter in more advanced JavaScript.

For now, use arrow functions for short callbacks and helper functions when they make the code clearer.

Use regular functions when you need normal function behavior or when it makes the lesson easier to understand.

Anonymous Functions

A function without its own name is called an anonymous function.

Example:

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

The function itself has no declared name after the function keyword.

It is stored in the variable:

greet

Anonymous functions are common as callbacks.

Functions as Values

JavaScript functions are values.

That means you can:

  • Store them in variables
  • Pass them to other functions
  • Return them from functions
  • Place them in objects

This is one reason JavaScript functions are very flexible.

You will see this idea more clearly with events and array methods.

What Is a Callback Function?

A callback is a function passed to another function so it can be used later.

Example:

function runTask(callback) {
    callback();
}

function showMessage() {
    console.log("Task complete");
}

runTask(showMessage);

Output:

Task complete

Here:

showMessage

is passed as a value.

Notice there are no parentheses:

runTask(showMessage);

If you wrote:

runTask(showMessage());

you would call showMessage immediately and pass its result instead.

Callbacks are very important in JavaScript events, timers, promises, and array methods.

Real Website Example: Button Click Function

Suppose your HTML contains:

<button id="buyButton">Buy Now</button>

JavaScript:

const buyButton = document.querySelector("#buyButton");

function handleBuyClick() {
    console.log("Product added to cart");
}

buyButton.addEventListener("click", handleBuyClick);

The function:

handleBuyClick

is passed to the event listener.

It runs later when the button is clicked.

You will study this properly in the JavaScript Events tutorial.

Real Website Example: Cart Total Function

Suppose:

const cart = [
    { price: 500, quantity: 2 },
    { price: 1000, quantity: 1 },
    { price: 250, quantity: 3 }
];

Create a reusable function:

function calculateCartTotal(items) {
    let total = 0;

    for (const item of items) {
        total += item.price * item.quantity;
    }

    return total;
}

Call it:

const total = calculateCartTotal(cart);

console.log(total);

Output:

2750

This combines functions with JavaScript loops.

Real Website Example: Check Free Shipping

function getsFreeShipping(cartTotal) {
    return cartTotal >= 1000;
}

Call:

console.log(getsFreeShipping(1500));

Output:

true

Use it in a condition:

if (getsFreeShipping(1500)) {
    console.log("Free shipping");
}

Real Website Example: Format Price

A website may need consistent price text.

function formatPrice(price) {
    return `₹${price}`;
}

Use:

console.log(formatPrice(1500));

Output:

₹1500

Later, you can replace this simple example with international number formatting when you study browser and JavaScript APIs.

Real Website Example: Validate a Required Field

function hasValue(value) {
    return value.trim() !== "";
}

Call:

console.log(hasValue("Riya"));

Output:

true

Call:

console.log(hasValue("   "));

Output:

false

This kind of helper function becomes useful in form validation.

Real Website Example: Product Availability Message

function getAvailabilityMessage(stock) {
    if (stock > 5) {
        return "In stock";
    }

    if (stock > 0) {
        return "Low stock";
    }

    return "Out of stock";
}

Call:

console.log(getAvailabilityMessage(3));

Output:

Low stock

The function returns as soon as one matching result is reached.

Functions Inside Functions

A function can be created inside another function.

Example:

function checkout() {
    function showMessage() {
        console.log("Order complete");
    }

    showMessage();
}

Call:

checkout();

Output:

Order complete

The inner function is normally available only inside the outer function.

You will study nested functions and closures later.

Rest Parameters

Sometimes a function needs to accept an unknown number of arguments.

JavaScript provides rest parameters:

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

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

    return total;
}

Call:

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

Output:

60

The rest parameter:

...numbers

collects the arguments into an array.

This is useful to recognize, but you do not need it for every beginner function.

Returning More Than One Piece of Information

A function returns one value.

That one value can be an object containing several pieces of information.

Example:

function calculateOrder(price, quantity) {
    const subtotal = price * quantity;
    const shipping = 100;
    const total = subtotal + shipping;

    return {
        subtotal,
        shipping,
        total
    };
}

Call:

const order = calculateOrder(500, 2);

console.log(order.total);

Output:

1100

This pattern becomes very useful as your projects grow.

Pure Function Idea for Beginners

A function is easier to reason about when its output depends on its inputs and it does not unexpectedly change outside values.

Example:

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

Given the same inputs:

calculateTotal(500, 2);

the result is always:

1000

This kind of predictable function is often easier to test and reuse.

You do not need to memorize the term yet. Focus on keeping functions clear and predictable.

Common Beginner Mistakes

Creating a Function but Never Calling It

This only defines the function:

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

You still need:

greet();

Forgetting Parentheses When Calling a Function

This:

greet

refers to the function itself.

This:

greet()

calls the function.

The difference becomes especially important with callbacks.

Confusing Parameters and Arguments

In:

function greet(name) {
    // ...
}

name is a parameter.

In:

greet("Amit");

"Amit" is an argument.

Forgetting return

Consider:

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

Call:

console.log(add(2, 3));

Output:

undefined

The function calculates the expression but does not return it.

Correct:

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

Writing Code After return

function test() {
    return "Done";

    console.log("Hello");
}

The console.log() cannot run.

Move required code before return.

Using a Local Variable Outside Its Function

Wrong:

function createUser() {
    const name = "Riya";
}

console.log(name);

name is local to the function.

Using the Same Function for Too Many Jobs

A function that validates data, changes the DOM, sends an API request, and calculates a price can become difficult to maintain.

Split unrelated jobs into smaller functions when possible.

Using Vague Function Names

Avoid:

function doStuff() {
    // ...
}

Prefer:

function calculateCartTotal() {
    // ...
}

Calling a Callback Instead of Passing It

Suppose:

function showMessage() {
    console.log("Hello");
}

For an event listener, this passes the function:

button.addEventListener("click", showMessage);

This calls it immediately:

button.addEventListener("click", showMessage());

Those are different actions.

Using Arrow Functions Everywhere Without Understanding Them

Arrow functions are useful, but they have different this behavior from regular functions.

Do not replace every function automatically.

Choose the syntax that makes the code correct and clear.

Forgetting Default Values

If a parameter may be missing, a default can prevent unexpected undefined values.

Example:

function greet(name = "Guest") {
    console.log(`Hello ${name}`);
}

Best Practices for JavaScript Functions

Give functions clear action-based names.

Keep each function focused on one main task.

Use parameters instead of hard-coding values when the function should be reusable.

Prefer returning results when other code needs those values.

Keep temporary variables inside the function when possible.

Avoid unnecessary changes to global variables.

Use default parameters when a fallback value makes sense.

Use arrow functions when they improve clarity, especially for short callbacks.

Do not make a function shorter at the cost of readability.

Prefer:

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

over a complicated function that performs several unrelated jobs.

Beginner Exercise

Create a function:

function greet(name) {
    return `Hello ${name}`;
}

Call it with your own name.

Store the result in a variable and print it.

Then create:

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

Call it with:

5
4

The result should be:

20

Challenge Exercise

Create this function:

function calculateFinalPrice(price, discountPercent) {
    // your code
}

It should:

  1. Calculate the discount amount.
  2. Subtract the discount from the price.
  3. Return the final price.

Test it with:

calculateFinalPrice(2000, 10);

The result should be:

1800

Extra Challenge

Create:

function getShippingCost(cartTotal) {
    // your code
}

Use these rules:

  • ₹2,000 or more → 0
  • ₹1,000 or more → 100
  • Below ₹1,000 → 200

Return the shipping cost instead of printing it inside the function.

Then call the function with several cart totals.

Frequently Asked Questions

What is a function in JavaScript?

A JavaScript function is a reusable block of code that performs a task and can be called when needed.

How do I create a function in JavaScript?

A basic function declaration looks like this:

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

Call it with:

greet();

What is a function parameter?

A parameter is a named value listed in the function definition.

function greet(name) {
    // ...
}

Here, name is a parameter.

What is a function argument?

An argument is the actual value passed when calling a function.

greet("Riya");

Here, "Riya" is an argument.

What does return do in JavaScript?

return sends a value back from a function and stops that function’s execution.

What happens if a function does not return anything?

The function returns undefined by default.

What is the difference between console.log and return?

console.log() displays a value in the Console.

return sends a value back to the code that called the function.

Can a function return more than one value?

A function returns one value, but that value can be an object or array containing several pieces of information.

What is a function expression?

A function expression stores a function in a variable.

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

What is an arrow function?

An arrow function is a shorter modern function syntax.

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

Are arrow functions the same as normal functions?

Not completely.

Arrow functions handle this differently and cannot be used as constructors.

For many small callbacks and helpers, arrow functions are useful.

What is a callback function?

A callback is a function passed to another function so it can be used later.

Callbacks are common in events, timers, array methods, promises, and APIs.

What is function scope?

Variables declared inside a function are normally available only inside that function and its inner scopes.

Can a function call another function?

Yes.

Functions can call other functions whenever that helps organize the program.

Can I put a function inside another function?

Yes.

A function can be declared inside another function.

This becomes important when you later learn closures.

What are default parameters?

Default parameters provide a fallback value when an argument is missing.

function greet(name = "Guest") {
    console.log(name);
}

What are rest parameters?

Rest parameters collect several arguments into an array.

function addAll(...numbers) {
    // ...
}

What should I learn after JavaScript functions?

Learn JavaScript arrays next. Arrays let you store ordered collections and work especially well with loops, functions, and array methods.

Summary

JavaScript functions group reusable code.

A basic function looks like:

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

Call it with:

greet();

Functions can accept parameters:

function greet(name) {
    console.log(`Hello ${name}`);
}

They can also return values:

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

You also learned about:

  • Function declarations
  • Function calls
  • Parameters
  • Arguments
  • Return values
  • Default parameters
  • Function scope
  • Local variables
  • Function expressions
  • Arrow functions
  • Callbacks
  • Rest parameters
  • Reusable website logic

Functions make larger JavaScript programs easier to organize, reuse, and maintain.

Continue Learning JavaScript

Previous Lesson: JavaScript Loops Explained

Course Home: JavaScript Tutorial for Beginners

Next Lesson: JavaScript Arrays Explained for Beginners

In the next lesson, you will learn how JavaScript arrays store multiple values, how indexes and length work, and how to add, remove, find, and update array items.

James Parker

James Parker

James Parker is a technology writer and WordPress enthusiast who shares practical guides on SEO, web development, AI tools, and digital growth. He focuses on creating easy-to-follow tutorials that help beginners and professionals build better websites and improve their online presence.