Reading list Switch to dark mode

    Declaring Function ( in JavaScript )

    Updated 15 October 2018

    What is Function?

    Function are the small chunks of modules designed to work for a specific task or purpose. Functions that we define for single purpose are easy to debug and use.These functions when defined for single purpose can be used again in future. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks.

    You can see below I have defined how these functions can be declared in javascript below :-

    Regular Function

    A function is declared with function keyword, function name and parameters.
    Here `function` is a keyword used to declare function, then followed by function name ( myFunc ) and inside parenthesis we have variables (parameter_1, parameter_2) whose value will be passed while declaration.

    Start your headless eCommerce
    now.
    Find out More
    // get sum of 2 variables
    function myFunc(parameter_1, parameter_2) {
    let parameter = parameter_1 + parameter_2;
    return parameter;
    }
    // function calling using function name
    myFunc();
    

    Anonymous function

    A function that has no name of itself and are declared with function keyword are called Anonymous function.
    These functions can be stored in a variable and are always invoked (called) using the variable name in which function is stored.

    // declaration of function and assigning it to a variable
    let x = function (a, b) {return a * b};
    // function called using variable name
    x(6, 4);

    Function() Constructor

    These are the functions that we can declare with a built-in JavaScript function constructor.
    We have to use Function keyword to declare a function in this type of function.

    // get sum of two variables/parameters from function
    let myFunc = new Function("parameter_1", "parameter_2", "return parameter_1 + parameter_2");
    // function calling using variable name
    let x = myFunc(6, 4);

    Self-Invoking Function

    When you want to invoke a function without being called then you can use Self-Invoking Functions as they are invoked (started) automatically, without being called.
    The only requirement is that it should be ended with ().

    // function calling itself
    (function () {
    var x = "Hello World!!";
    })();
    
    or
    
    // function calling itself
    (function () {
    var x = "Hello World!!";
    }());
    

     

    That’s all for today on how to declare functions in JavaScript, if you still have issues feel free to comment below for any query.

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home