A function is a block of code (set of statements) designed to perform a specific task. Functions allow us to write more maintainable code with the use of small pieces of code following the DRY (Don't Repeat Yourself) rule. It provides the means to structure larger programs, to reduce repetition.
A function can be written in 2 ways,
- Function Declaration
- Function Expression
Function Declaration
This defines a named function variable without requiring variable assignment i.e. it defines a function. Just as variable declaration must start using let or var, function declaration starts with a function keyword.
A function declaration consists of function keyword, followed by:
- the name of the function
- parameter(s) passed to the function, enclosed in parentheses and separated by comma if more than one.
- the JavaScript statements that define the function, enclosed in curly brackets, {...}.
N/B: Parameters are not always passed to functions and for a function to be used, it has to be invoked(called). The return keyword is optional. But the function will return anyway once all statements in its body are done executing, even if the return keyword is not specified.
Function Expression
A function can also be defined as an expression. Functions are first-class objects and can be assigned to a variable as an expression, passed as a parameter, and much more. In short, a function expression is defined by assigning a function definition to a variable.
N/B: A function expression is said to be anonymous when it doesn't have a name. Anonymous Function Expressions are used to create callback functions while Named Function Expressions are useful for creating recursive functions. Function Expression is quite useful in the real world. It is also used to create a coding pattern called IIFE(Immediately Invoked Function Expression).
I hope this helped. Watch out for Part 2.
See ya ๐