JavaScript Function Definitions

Functions in JavaScript are blocks of code designed to perform a particular task. They can be defined using function declarations, function expressions, or arrow functions.

Key Topics

Function Declaration

Function declarations use the function keyword, followed by a name and a code block.

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

Output

> Hello, World!

Explanation: The greet function is defined and then called, logging a greeting to the console.

Function Expression

A function expression assigns an anonymous or named function to a variable.

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

Output

> Hello from a function expression!

Explanation: The greet variable holds a function, which is then invoked.

Arrow Function

Arrow functions, introduced in ES6, provide a concise syntax for defining functions.

const greet = () => {
    console.log("Hello from an arrow function!");
};
greet();

Output

> Hello from an arrow function!

Explanation: The arrow function is assigned to the greet variable and invoked, logging a message.

JavaScript Usage in DOM

Below is a complete DOM example using a function to handle a button click event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Function Definitions in DOM</title>
</head>
<body>
    <button onclick="showMessage()">Click Me</button>
    <p id="message"></p>

    <script>
        function showMessage() {
            document.getElementById("message").textContent = "Hello from the DOM!";
        }
    </script>
</body>
</html>

Key Takeaways

  • Function Declarations: Use the function keyword to define reusable code blocks.
  • Function Expressions: Store functions in variables for flexible usage.
  • Arrow Functions: Provide a concise syntax and lexical this binding.
  • DOM Integration: Use functions to add interactivity to web pages.