Skip to content

Instantly share code, notes, and snippets.

@siddrc
Last active May 18, 2018 21:03
Show Gist options
  • Save siddrc/740628c3d8d3d57ce815acf095a5da0a to your computer and use it in GitHub Desktop.
Save siddrc/740628c3d8d3d57ce815acf095a5da0a to your computer and use it in GitHub Desktop.
What is a function

functions

A function in simple terms takes an input, does something and gives a output. In simple terms there is always some sort of action inside a function.

A function may or may not take arguements.

  1. If it takes one argument it's a monoadic function
  2. If it takes then it is called a two diadic function
  3. More than 2 then it is a polyadic function.

Same function thought process applies in Javascript. In practice, JS does not support function overloading. In Javascript a function generally looks like:

function nameOfFunction(){
 //some code for performing or doing something.
}
function nameOfFunctionMono(arg1){
    //monoadic function 
   //some code for performing or doing something.
}
function nameOfFunctionDia(arg1,arg2){
   //diadic function 
  //some code for performing or doing something.
}
function nameOfFunctionPoly(arg1,arg2,arg3){
  //polyadic function 
 //some code for performing or doing something.
}

As you can see function keyword is used to declare a function All the below declarations are valid.

const nameOfFunction = function(){
//some code for performing or doing something.
}
/**/

/*  A function can contain another function, but only the outer function will know about it, 
  except if you are in a `constructor` and you are binding the function to this.More on this 
  in Constructor.MD */

const nameOfFunctionInner = function(){
       //some code for performing or doing something.
     function test(args){
       console.log(`${args}`)
     }
     test('tryme')
}

/* A function can take another function as an argument.*/
function fun1(functionArgs){
 functionArgs()
}
function fun2(){
  console.log(`hello world`)
}
function fun3(){
  console.log(`hello`)
}
fun1(fun2)
fun1(fun3)
/*
Javascript has something called as higher order functions, 
where a simple function can take another function as an argument, this is also because Javascript treats functions as values.
*/

In practice we always strive to make pure functions in Javascript, which means whenever we pass an object as an argument to a function we do not change the state of the argument object at all.

Please click the link below for more thoughts on higher order functions in JS.

Links https://youtu.be/BMUiFMZr7vk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment