JavaScript Functions

Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They help organize code, improve readability, and promote reusability.

Key Topics

Defining Functions

A function is defined using the function keyword followed by a name, parentheses, and a code block. Functions can be called multiple times.

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

Output

> Hello!

Explanation: The greet function prints "Hello!" to the console when called. You can call it as many times as you need.

Parameters and Return Values

Functions can accept parameters and return values, making them flexible and versatile.

function add(a, b) {
    return a + b;
}
let sum = add(3, 4);
console.log("Sum: ", sum);

Output

> Sum: 7

Explanation: The add function takes two parameters a and b, and returns their sum. The returned value is then logged to the console.

Function Expressions and Arrow Functions

Functions can also be defined as expressions or using the arrow function syntax, offering concise and flexible ways to define functions.

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

const square = (n) => n * n;

console.log("Multiply: ", multiply(2, 3));
console.log("Square: ", square(5));

Output

> Multiply: 6

> Square: 25

Explanation: The multiply variable stores a function expression, and square is defined using an arrow function for concise syntax. Both can be called like regular functions.

JavaScript Usage in DOM

This DOM-based example shows how functions can be used to interact with webpage elements dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Functions in DOM</title>
</head>
<body>
    <h1>Function Demo</h1>
    <button onclick="showMessage()">Show Message</button>
    <p id="message"></p>

    <script>
        function showMessage() {
            document.getElementById("message").textContent = "Functions make code reusable!";
        }
    </script>
</body>
</html>

Key Takeaways

  • Function Definition: Use function keyword to create reusable code blocks.
  • Parameters and Returns: Functions can accept inputs and return outputs.
  • Function Expressions: Assign functions to variables or use arrow syntax.
  • DOM Integration: Utilize functions to dynamically update webpage content.