Geek Slack

Introduction to JavaScript
    About Lesson




    JavaScript Functions


    JavaScript Functions

    Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code designed to perform a particular task. Functions can take inputs (parameters) and return an output (result).

    Defining a Function

    A function can be defined using the function keyword followed by a name, a list of parameters (optional), and a block of code to execute.

    Example:

    function greet() {
        console.log("Hello, World!");
    }
    
    // Calling the function
    greet(); // Output: Hello, World!

    Function Parameters

    Functions can accept inputs called parameters. These parameters allow you to pass data to the function when it is called.

    Example:

    function greet(name) {
        console.log("Hello, " + name + "!");
    }
    
    // Calling the function with a parameter
    greet("Alice"); // Output: Hello, Alice!

    Return Values

    A function can return a value back to the caller using the return statement.

    Example:

    function add(a, b) {
        return a + b;
    }
    
    // Calling the function and storing the return value
    let result = add(5, 3);
    console.log(result); // Output: 8

    Function Expressions

    Functions can also be defined as expressions and assigned to variables. These are called function expressions.

    Example:

    const square = function(x) {
        return x * x;
    };
    
    // Calling the function expression
    console.log(square(4)); // Output: 16

    Arrow Functions

    ES6 introduced a new way to define functions using arrow functions. Arrow functions are a shorter syntax and do not have their own this value.

    Example:

    const multiply = (a, b) => {
        return a * b;
    };
    
    // Calling the arrow function
    console.log(multiply(2, 3)); // Output: 6

    Immediately Invoked Function Expressions (IIFE)

    An IIFE is a function that runs as soon as it is defined. It is often used to create a new scope and avoid polluting the global namespace.

    Example:

    (function() {
        console.log("IIFE executed!");
    })(); // Output: IIFE executed!

    Functions as First-Class Citizens

    In JavaScript, functions are first-class citizens. This means they can be stored in variables, passed as arguments to other functions, and returned from functions.

    Example:

    function executeFunction(func) {
        func();
    }
    
    const sayHello = function() {
        console.log("Hello!");
    };
    
    // Passing a function as an argument
    executeFunction(sayHello); // Output: Hello!

    Understanding how to define and use functions is crucial for mastering JavaScript. Functions help you organize your code, make it more readable, and enable you to reuse code efficiently.