JavaScript Functions

A function is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, a function can be written once and called (used) whenever needed.

Real-life analogy: A coffee machine is a function. Every time a button is pressed, it performs the same steps (heat water, brew coffee, pour into cup). The task is defined once, and it executes on demand.

Why Use Functions?

  • Reusability — Write code once, use it multiple times
  • Organization — Break large programs into smaller, manageable pieces
  • Maintainability — Update logic in one place instead of many
  • Readability — Named functions make code self-documenting

Defining and Calling a Function

A function is defined using the function keyword, followed by a name, parentheses, and a code block.

Syntax:

function functionName() {
  // Code to execute
}
// Defining the function
function greet() {
  console.log("Hello! Welcome to the tutorial.");
}

// Calling the function
greet();  // Output: Hello! Welcome to the tutorial.
greet();  // Can be called multiple times
greet();

Function Parameters and Arguments

Parameters are placeholders listed in the function definition. Arguments are the actual values passed in when the function is called.

// "name" is a parameter
function greetUser(name) {
  console.log("Hello, " + name + "!");
}

// "Priya" and "Amit" are arguments
greetUser("Priya");  // Hello, Priya!
greetUser("Amit");   // Hello, Amit!

Multiple Parameters

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

addNumbers(10, 20);  // 30
addNumbers(5, 7);    // 12

Return Statement

The return statement sends a value back from the function to wherever it was called. Once a return is reached, the function stops executing.

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

let result = multiply(4, 5);
console.log(result);  // 20

// The returned value can also be used directly
console.log(multiply(3, 7));  // 21

A Function Without Return

If a function has no return statement (or returns nothing), it returns undefined.

function sayHi() {
  console.log("Hi!");
}

let value = sayHi();
console.log(value);  // undefined

Default Parameters

Default parameters allow a function to use a fallback value when no argument is provided for that parameter.

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

greet("Rahul");  // Hello, Rahul!
greet();          // Hello, Guest! (default used)

Function Expressions

A function can also be stored in a variable. This is called a function expression. The function itself has no name — it is anonymous.

const square = function(num) {
  return num * num;
};

console.log(square(5));   // 25
console.log(square(9));   // 81

Arrow Functions (ES6)

Arrow functions are a shorter, more modern syntax for writing function expressions. They use => instead of the function keyword.

// Traditional function
const add = function(a, b) {
  return a + b;
};

// Arrow function
const add = (a, b) => a + b;

console.log(add(3, 4));  // 7

Arrow Function Shorthand Rules

  • If there is only one parameter, parentheses are optional: num => num * 2
  • If the function body is a single expression, curly braces and return are optional
const double = num => num * 2;
console.log(double(7));   // 14

const greet = name => "Hello, " + name;
console.log(greet("Sita"));  // Hello, Sita

Scope in Functions

Variables declared inside a function are local to that function. They cannot be accessed from outside.

function calculateTax() {
  let rate = 0.18;  // Local variable
  return rate;
}

// console.log(rate);  // Error! rate is not defined outside the function

Global vs Local Variables

let message = "I am global";  // Global variable

function showMessage() {
  let localMsg = "I am local";  // Local variable
  console.log(message);         // Accessible
  console.log(localMsg);        // Accessible
}

showMessage();
// console.log(localMsg);  // Error! Cannot access local variable here

Function Calling Itself (Recursion)

A function that calls itself is called a recursive function. It is useful for tasks that naturally repeat with smaller inputs, like counting down or calculating factorials.

function countdown(number) {
  if (number <= 0) {
    console.log("Done!");
    return;
  }
  console.log(number);
  countdown(number - 1);  // Function calls itself
}

countdown(5);
// Output: 5, 4, 3, 2, 1, Done!

Functions as Arguments (Callback Functions)

Functions can be passed as arguments to other functions. The function passed in is called a callback. This is a core concept in JavaScript, especially for events and asynchronous programming.

function runTask(task) {
  console.log("Starting task...");
  task();  // Call the function passed in
  console.log("Task complete.");
}

function printReport() {
  console.log("Printing the report.");
}

runTask(printReport);
// Output:
// Starting task...
// Printing the report.
// Task complete.

Comparing Function Types

TypeSyntaxUse Case
Function Declarationfunction name() {}General purpose, hoisted
Function Expressionconst name = function() {}Stored in variable, not hoisted
Arrow Functionconst name = () => {}Short, modern syntax, callbacks

Practical Example — Temperature Converter

function celsiusToFahrenheit(celsius) {
  return (celsius * 9/5) + 32;
}

function fahrenheitToCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5/9;
}

console.log(celsiusToFahrenheit(100));   // 212 (Boiling point)
console.log(celsiusToFahrenheit(0));     // 32  (Freezing point)
console.log(fahrenheitToCelsius(98.6));  // 37  (Body temperature)

Key Points to Remember

  • Functions are reusable blocks of code that perform a specific task
  • Define a function with the function keyword, then call it by name with ()
  • Parameters receive values (arguments) when the function is called
  • The return statement sends a value back from the function
  • Default parameters provide fallback values when arguments are missing
  • Arrow functions offer a shorter syntax for writing functions
  • Variables inside a function are local — not accessible outside
  • Functions can be passed as arguments to other functions (callbacks)

Leave a Comment

Your email address will not be published. Required fields are marked *