Javascript

Reusing code with functions

Reusing Code with Functions in JavaScript

Reusing Code with Functions in JavaScript: Why and How

When writing code, you often find yourself doing the same task multiple times. Instead of repeating the same lines over and over, JavaScript functions let you package a block of code into a reusable unit.

This not only saves time but also keeps your code cleaner, easier to maintain, and less error-prone.


What is a Function?

A function is a reusable block of code designed to perform a particular task. You can call (execute) it as many times as you want, passing different inputs and getting outputs.


How to Declare a Function

Here’s the basic syntax:

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

To run the function, you call it by name:

js
sayHello(); // Output: Hello, world!

Functions with Parameters

Functions can accept inputs (called parameters), making them flexible.

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

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


Functions that Return Values

Functions can also send back results using the return statement.

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

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


Why Use Functions?

  • Avoid repetition: Write code once and reuse it.

  • Organize your code: Functions help break complex tasks into smaller, manageable parts.

  • Easier debugging: Fix or update code inside one function instead of multiple places.

  • Improve readability: Descriptive function names explain what code does.


Function Expressions & Arrow Functions (Modern Syntax)

Besides the function keyword, you can create functions as expressions or arrow functions:

js
// Function expression
const multiply = function(x, y) {
return x * y;
};

// Arrow function (concise)
const multiplyArrow = (x, y) => x * y;

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


Real-World Example: Reusable Calculator Functions

js
function subtract(a, b) {
return a - b;
}

function divide(a, b) {
if (b === 0) {
return "Error: Division by zero";
}
return a / b;
}

console.log(subtract(10, 3)); // 7
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // Error: Division by zero


Summary

Functions are the building blocks for reusable, modular JavaScript code. Learning to write and use functions effectively will make your programming journey much smoother!


Want to try?

  • Write a function that converts Celsius to Fahrenheit.

  • Create a function that greets users differently based on the time of day.

  • Build simple calculator functions like add, subtract, multiply, divide.

Leave a Reply

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