Functions in Javascript

Starting with javascript, you may have felt once, like "why the function is looking so unfamiliar?, what's wrong with the syntax?, why it doesn't have any name? ".
I have also felt like that. So in this blog, I'll try to make you familiar with function in javascript.

Functions

As we keep on listening, functions are the group of instructions that performs some specific task.

  • In javascript, it's also the same but, they play some special role.
    They are one of the fundamental building blocks.

  • The syntax of functions in javascript is a little different, from other languages, that we have learned, like java, c, c++, etc.

    Here is the general syntax of function in javascript.

        function f1( number ){  
            return number*number;
      }
    
  • In the above example,

    ** function ** is the keyword.
    ** f1 ** is the name of the function .
    ** number ** is the parameter of function.

    Different forms of functions in javascript

    Function statement

    The general way of creating a function in javascript is called function statement.
    e.g.,

      function f1( number ){
            return number*number;
      }
    
  • The other term of the function statement is ** Function Declaration **.

    Function Expression

    The way of creating a function by putting the function in a variable while defining it.

      var b = function ( number ){
            return number*number;
      }
    

    Anonymous Function

    Those function which doesn't have a name are called anonymous function. It doesn't have its own identity.

      function (){
    
      }
    
  • They are used in a place where they are used as value.

  • We can assign function to a variable it'll act like a value.

    Named Function

    It's exactly the function expression, but when a function is passed to any variable, it has a name.

      var a = function abc (){
    
      }
    
  • We can call this function by ** a() **

  • Calling **abc()** will give you error.

    Arrow function

  • They were introduced in ES6.

  • They allow us to write in shorter syntax of function. ``` let myFun = (a, b) => { a * b; console.log('Hey guys'); } myFun(5,6); ```

  • If you have single instruction inside the function you can remove the braces.

    As you read till here, bonus for you.

    Higher order function

  • Function takes another function as an argument.

    First class function

    Passing function as an argument or values to other function.

      var b = function(num){
          console.log(num);
      }
      function xyz(){
    
      }
      b(xyz);
    
  • Because of this the functions are also called as the **First Class citizen** in javascript.

    Thanks for reading this blog. I hope this blog helped you in learning some new stuffs.

    Connect me on twitter.

Did you find this article valuable?

Support Anurag's blog by becoming a sponsor. Any amount is appreciated!