Instagram
youtube
Facebook
Twitter

Function Basics

In JavaScript, a function is one of the fundamental building blocks. A function is essentially a block of code designed to perform a specific task. It allows you to reuse code, organize logic, and make your programs more modular and maintainable.

What is a Function?

A function is a reusable set of instructions that you define once and call whenever needed. This reduces repetition in your code and makes it easier to update and debug. Functions can take input values (called parameters) and return an output value (or nothing at all).

Why Use Functions?

Functions help in:

  • Code Reusability: You can write a function once and use it multiple times.
  • Modularity: Break your code into smaller parts, making it easier to read, maintain, and debug.
  • Abstraction: Hide complex logic inside functions, so you only need to focus on what a function does, not how it does it.

Declaring a Function

In JavaScript, you can declare a function using the function keyword followed by:

  • The name of the function.
  • A set of parentheses (which may or may not include parameters).
  • A block of code (inside curly braces {}) that defines the function's behavior.

Example of Function Declaration:

function greet() {
  console.log("Hello, welcome to Coders Daily!");
}

Here:

  • greet is the name of the function.
  • The function does not take any parameters.
  • Inside the function, there’s a line of code that prints a greeting message.

Calling (Executing) a Function

Once a function is declared, you can call or invoke it by using its name followed by parentheses.

Example:

greet(); 
// Output: Hello, welcome to CodersDaly!

Functions with Parameters

Functions can accept parameters, which are variables that represent values you pass into the function. These parameters allow the function to be more flexible and dynamic.

Example with Parameters:

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

greetUser("Dev"); // Output: Hello, Dev!
greetUser("Rahul"); // Output: Hello, Rahul!

In this example:

  • The function greetUser takes a parameter called name.
  • When calling the function, you provide an argument ("Pinki", "John") that is used inside the function to generate a personalized greeting.

Functions with Multiple Parameters

A function can also accept multiple parameters. These parameters are separated by commas.

Example with Multiple Parameters:

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

const sum = addNumbers(5, 10);
console.log(sum); // Output: 15

In this example:

  • The function addNumbers takes two parameters: a and b.
  • It returns the sum of the two numbers by using the return keyword, which passes the result back to wherever the function was called.

Real-Time Example: Calculate Discount

Here’s a practical, real-world example of how a function can be used to calculate the price of a product after applying a discount:

function calculateDiscount(price, discountRate) {
  const discount = price * (discountRate / 100);
  const finalPrice = price - discount;
  return finalPrice;
}

const originalPrice = 100;
const discountRate = 10;

const discountedPrice = calculateDiscount(originalPrice, discountRate);
console.log("Discounted Price: $" + discountedPrice); // Output: Discounted Price: $90

In this example:

  • The calculateDiscount function takes two parameters: price and discountRate.
  • It calculates the discount, subtracts it from the original price, and returns the final discounted price.

Returning Values from Functions

A function can return a value using the return statement. Once the function hits the return statement, it stops executing and returns the value specified. This returned value can be stored in a variable or used immediately.

Example of Returning a Value:

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

const result = multiply(3, 4); // result is 12
console.log(result); // Output: 12

In this example, the multiply function returns the product of a and b, which is then stored in the variable result.


Anonymous Functions

You can also define anonymous functions in JavaScript. These are functions without a name and are often used as arguments in other functions (like event handlers or callbacks).

Example of Anonymous Function:

const greeting = function() {
  console.log("Hello from an anonymous function!");
};

greeting(); // Output: Hello from an anonymous function!

Here, we assign an anonymous function to the variable greeting and call it later using the variable name.

Real-Time Example: Anonymous Function in Array Methods

Anonymous functions are especially useful with JavaScript array methods like map, filter, and reduce. Here’s an example where we use an anonymous function to square the numbers in an array:

const numbers = [1, 2, 3, 4, 5];

const squaredNumbers = numbers.map(function(number) {
  return number * number;
});

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

In this example, an anonymous function is passed to the map method, which applies the function to each element in the numbers array.


Function Expressions vs. Function Declarations

There are two ways to define a function:

  1. Function Declaration: Declares a function with a name.
  2. Function Expression: Defines a function and assigns it to a variable.

Example of Function Declaration:

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

Example of Function Expression:

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

The difference lies in how JavaScript hoists the functions. Function declarations are hoisted, meaning they can be called before they are defined in the code, while function expressions are not hoisted and can only be called after the function has been defined.


Conclusion

Functions are one of the most powerful and essential features in JavaScript. They allow you to organize your code, reuse logic, and make your code more modular. As you continue learning, you'll see that functions form the basis for many advanced concepts in JavaScript, such as callbacks, closures, and asynchronous programming. In the next lessons, you will learn about function parameters, return values, and more advanced features like arrow functions and higher-order functions.