JavaScript Functions

Write reusable logic with function patterns.

declarationarrow functionsreturn values

Table of Contents

JavaScript Functions Tutorial (Beginner -> Advanced)

Functions are reusable blocks of code designed to perform a specific task. Instead of repeating the same logic, you define it once and call it whenever needed. This keeps your code clean, modular, and easier to maintain.

1. What is a Function?

A function is declared using the function keyword.

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

greet(); // calling the function

When you call greet(), the code inside it executes.

2. Function with Parameters (Input)

Functions can take inputs called parameters.

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

greet("John");
greet("Priya");

Here, name is a parameter, and values passed are arguments.

3. Function with Return Value (Output)

Functions can return results using return.

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

let result = add(5, 3);
console.log(result);

Once return executes, the function stops.

4. Function Expression

You can store a function inside a variable.

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

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

5. Arrow Functions (Modern JavaScript)

Short and cleaner syntax.

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

// Short form (implicit return):
const square = x => x * x;

6. Default Parameters

Set default values if no argument is passed.

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

greet(); // Hello Guest

7. Rest Parameters

Handle multiple arguments.

function sum(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}

console.log(sum(1, 2, 3, 4));

8. Callback Functions

A function passed as an argument to another function.

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

function sayBye() {
    console.log("Goodbye!");
}

greet("John", sayBye);

9. Nested Functions

Functions inside other functions.

function outer() {
    function inner() {
        console.log("Inside inner function");
    }
    inner();
}

outer();

10. Visual Understanding

Functions follow a simple flow: Input (arguments) -> Processing (function body) -> Output (return value). This mental model helps when debugging and designing reusable logic.

11. Real-Life Example

function calculateTotal(price, taxRate) {
    return price + (price * taxRate);
}

let total = calculateTotal(100, 0.18);
console.log("Final Price:", total);

12. Best Practices

  • Use meaningful names like calculateTotal() instead of calc().
  • Keep functions small and focused on one task.
  • Avoid unnecessary global variables inside functions.
  • Use arrow functions for short logic and callbacks.

13. When to Use Functions

Functions are useful when you need to reuse code, organize logic, or break large problems into smaller steps. They are the foundation for advanced concepts like events, APIs, and frameworks.

Related Topics

Connect this topic with Loops, Arrays, and Asynchronous JavaScript to write reusable real-world logic.

10 Functions Interview Q&A

1Function declaration vs expression?easy
Answer: Declaration is hoisted fully; expression depends on assignment timing.
2What is pure function?medium
Answer: Same input gives same output with no side effects.
3Arrow function main benefit?easy
Answer: Concise syntax and lexical this behavior.
4Default parameters purpose?easy
Answer: Provide fallback values when args are missing.
5What is callback function?medium
Answer: Function passed as argument to another function.
6What is higher-order function?medium
Answer: Function that receives/returns other functions.
7Can function return object/array?easy
Answer: Yes, functions can return any JS value.
8What is IIFE?hard
Answer: Immediately Invoked Function Expression runs instantly after definition.
9Why keep functions small?easy
Answer: Easier testing, readability, and reuse.
10Functions used with arrays for?easy
Answer: map/filter/reduce style transformations.

10 Functions MCQs

1

Which defines arrow function?

Afunction => ()
B() => {}
Cfunc(){}
Darrow(){}
Explanation: Arrow syntax uses =>.
2

Default params apply when arg is:

A0
Bundefined
Cfalse
D""
Explanation: Defaults trigger for undefined.
3

A callback is:

Aglobal variable
Bfunction passed into another
Cloop type
Dobject key
Explanation: callbacks are function arguments.
4

Function declaration is:

Anot hoisted
Bhoisted
Cprivate only
Ddeprecated
Explanation: function declarations are hoisted.
5

Higher-order function:

Areturns number only
Bworks with functions as values
Cis loop
Dis class
Explanation: takes/returns functions.
6

A function can return:

Astring only
Bany JS type
Cnothing
Dboolean only
Explanation: returns any value type.
7

IIFE runs:

Aon event only
Bimmediately after creation
Con timer only
Dnever
Explanation: IIFE executes instantly.
8

Best for reusable logic:

Aif only
Bfunctions
Cswitch only
Dalert
Explanation: functions encapsulate reusable behavior.
9

Arrow functions have:

Aown this always
Blexical this
Cno params
Dno return
Explanation: arrow captures surrounding this.
10

Next topic after functions here:

AArrays
BSEO
CBootstrap
DMedia
Explanation: learning path proceeds to arrays.