What are JavaScript Functions? See Examples

In JavaScript, functions are blocks of reusable code that perform a specific task. Functions help reduce repetition, organize code, and make programs easier to maintain.


1. Function Declaration

A basic way to define a function:

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

greet("Alice"); // Output: Hello, Alice!
  • name is a parameter, a placeholder for input.
  • Values passed when calling the function are called arguments.

2. Function Expression

Functions can also be stored in variables:

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

console.log(add(5, 3)); // Output: 8
  • Function expressions are often used for callbacks or event handling.

3. Arrow Functions (ES6)

A concise syntax for defining functions:

const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20
  • Arrow functions are shorter and do not have their own this context.

4. Return Statement

Functions can return values for further use:

function square(num) {
    return num * num;
}
let result = square(6);
console.log(result); // 36
  • Without return, a function returns undefined by default.

5. Default Parameters

Set default values for parameters to avoid undefined:

function greetUser(name = "Guest") {
    console.log("Welcome, " + name);
}
greetUser();       // Output: Welcome, Guest
greetUser("Bob");  // Output: Welcome, Bob

6. Practical Tips

  • Use functions to avoid repeating code and make it more readable.
  • Use arrow functions for shorter callbacks, but use regular functions when you need this.
  • Keep functions focused on one task only, making them easier to debug and test.

Functions are the building blocks of JavaScript programs. Mastering them allows you to write cleaner, reusable, and efficient code.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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