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.
- If it takes one argument it's a monoadic function
- If it takes then it is called a two diadic function
- 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.