JavaScript Functions

1. Function Declaration


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function greet() {
            console.log("Hello, World!");
        }
        greet();// Output: Hello, World!
    </script>
</body>
</html>
                        

2. Function with Parameters


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function greet(name) {
            console.log("Hello, " + name + "!");
        }
        greet("AIT");
        // Output: Hello, AIT!
    </script>
</body>
</html>
                       

3. Function with Return Value


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function add(a, b) {
            return a + b;
        }
        let sum = add(5, 3);
        console.log(sum);
        // Output: 8
    </script>
</body>
</html>
                       

4. Function Expression


<!DOCTYPE html>
<html lang="en">
<body>
<script>
    const multiply = function(a, b) {
        return a * b;
    };
    let product = multiply(4, 2);
    console.log(product);
    // Output: 8
</script>
</body>
</html>
                       

5. Arrow Function


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        const divide = (a, b) => {
            return a / b;
        };
        let result = divide(10, 2);
        console.log(result);
        // Output: 5
    </script>
</body>
</html>
                       

6. Function as a Parameter (Callback)


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function processUserInput(callback) {
            let name = "AIT ";
            callback(name);
        }
        processUserInput(function(name) {
        console.log("Hello" + name + "!");
        });
        // Output: Hello, AIT!
    </script>
</body>
</html>
                        

7. Immediately Invoked Function Expression (IIFE)


<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        (function() {
            console.log("This is an IIFE!");
        })();
        // Output: This is an IIFE!
    </script>
</body>
</html>
                        

8. Default Parameters

 
<!DOCTYPE html>
<html lang="en">
<body>
    <script>
        function greet(name = "Guest") {
            console.log("Hello, " + name + "!");
        }
        greet();
        // Output: Hello, Guest!
</script>
</body>
</html>