A function definition is a regular binding where the value of the binding is a function.For example,
const square = function(x) {
return x * x;
};
- Each function will have both a definition and declaration.
- Declaration is basically you simply telling JS to make a particular function, and witholding the info on how the function will process your arguments.
function declare();
- Definition on the other hand, will tell JS exactly what your function will do with the input arguments.
function declare(){
console.log("Hi, I am Param");
}
-
Scope : Each variable will have a scope, usually global or local.
- Global scope indicates that the variable can be used by any function or block of code in our program.
- Local scope means that the variable is valid only within our code block, for example, inside a function. No code segment outside our function(in the above example) will be able to access a local variable.
- Note : Nesting of functions is possible, i.e., you can declare functions within functions, code blocks within other code blocks. This means that we can have a lot of local variables and global variable pairs too.
The arrow notation :
- Quoting from EloquentJS, "Thereβs a notation for functions, which looks very different from the others. Instead of the function keyword, it uses an arrow (=>) ."
-
Its syntax goes like :
const power = (base, exponent) => {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};- The arrow comes after all the function arguments, and is followed by the normal function body, as in the usual syntax that we have seen above.
Optional arguments
- A function can be given additional arguments, in the sense you can provide 3 arguments to it, when it has only one argument. This is perfectly fine, and JS will ignore you and do your work.
- Also, you can make define a function as
const bio = (name, age = 25) =>{ //age is an optional argument
console.log("Name :" + name + " Age :" + age);
}
//call 1
bio("param");
//call 2
bio("param",19);
//output 1 : Name :param Age : 25
//output 2 : Name :param Age : 19
In the above function, both calls are perfectly valid.
Recursion
As stated above, you can have functions calling other functions, and even itself within the function. This way of calling a function within itself is known as recursion.
For recursion, the function will have 2 main things :
* A base condition, on which it will exit the recursive call
* The call to function itself
* Optional : Any other logic/programming, if required
function power(base, exponent) {
if (exponent == 0) {
return 1;
} else {
return base * power(base, exponent - 1);
}
}
console.log(power(2, 3));
// β 8
Review
I would love your feedback on this guys, and feel free to revert back to me with any recommendations that you have for me. You can also mail me at padb19122000@gmail.com .
Top comments (0)