What is function
Function is a separate block of code that may or may not get argument(s), or may or may not return something. It is executed only when it is called. Functions are written to reuse. Write the code once and use it many time.
Function Definition
- Javascript function is defined with keyword "function"
- Than function name
- Than comma separated list of parameters inside parentheses.
- And finally body of function enclosed with curly braces.
body
}
Now call this function as
Output: Area is: 50.24
Same function return different result based on different parameters.
Local Variable
Parameters of a function become local variable to store passed values to this function. These local variables cannot be accessed outside the called function. Local variables are created when the function is invoked and destroyed when then function ends.
Arrow Function
Arrow function reduce the code and make then function more shorter. It was introduced by ES6.
Traditional Function Vs Arrow Function
Below is the same function written above to calculate area of circle.
Now we will make it shorter by converting it to arrow function. First remove keyword "function" and insert => after parentheses.
No need parentheses in case of single parameter
Now if there is only one expression, then remove curly braces and return keyword as.
Post a Comment