JavaScript Functions


What is a Function?

A function is a block of reusable code that performs a specific task.

Instead of repeating the same code, we write it once inside a function and call it when needed.

Why Use Functions?

  • Reuse code (Write once, use many times)
  • Make code organized and readable
  • Break programs into smaller parts
  • Avoid repetition

Function Syntax

Basic Function Declaration

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

greet(); // Call the function

Parameters and Arguments

You can pass values to a function using parameters (placeholders).

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

greet("Alice"); // Output: Hello, Alice
greet("Bob");   // Output: Hello, Bob

Return Statement

Use return to send a value back from the function.

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

let result = add(5, 3);
console.log(result); // Output: 8

Once a return is hit, the function exits.

Function Expressions

Functions can also be assigned to variables.

const multiply = function(x, y) {
  return x * y;
};

console.log(multiply(4, 5)); // Output: 20

Arrow Functions (ES6)

A shorter way to write function expressions.

const square = (n) => {
  return n * n;
};

console.log(square(6)); // Output: 36
const square = n => n * n;

Default Parameters

You can set default values for parameters.

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

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

Function Scope

Variables defined inside a function are not accessible outside.

function sayHi() {
  let message = "Hi!";
  console.log(message);  // OK
}

sayHi();
// console.log(message); // ❌ Error: message is not defined

Nested Functions

Functions can be defined inside other functions.

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

outer(); // Output: Hello from inner

Anonymous Functions

A function without a name — used often in event handlers or callbacks.

setTimeout(function() {
  console.log("Executed after 2 seconds");
}, 2000);

Callback Functions

A callback is a function passed as an argument to another function, to be executed later.

function greetUser(name, callback) {
  console.log("Hi " + name);
  callback();
}
                                
function showMessage() {
  console.log("Welcome to our site!");
}

greetUser("Alice", showMessage);

Immediately Invoked Function Expression (IIFE)

A function that runs immediately after it's defined.

(function() {
  console.log("IIFE runs instantly!");
})();

Useful for:

  • Avoiding global variable pollution
  • Creating private scopes

Summary

Feature Statement Notes
Function Declaration function add() {} Hoisted (can be used before defined)
Function Expression const add = function() {} Not hoisted
Arrow Function const add = (a, b) => a + b Short, modern syntax
Default Parameters function(a = 1) {} Sets fallback value
Return Value return x * y Sends result back
Callback Function func(callback) Used for async/events
IIFE (function() {})(); Runs immediately

🧪 Practice Exercise:

Task:

  1. Write a function isEven(number) that returns true if the number is even, else false.
  2. Write a function greetUser(name, time) that returns "Good Morning/Evening, [name]" based on the time (AM/PM).
  3. Create an arrow function that adds two numbers and returns the result.