Let’s Explore Function Definitions
Note: This article was originally published on Medium.
Before exploring methods for defining functions, let’s remind the basic terms used in functions.
Photo by Matthew Brodeur on Unsplash
A Function is a block of code to do a specific task so that we can reuse this code whenever we need it without rewriting the same code again and again.
In more formal terms, a function takes some data as input, performs the calculations on input and returns the processed result as output.
When we need to use the function in our program, we can call it by its identifier and pass arguments to its parameters. Parameters are variables which function use as input.
Parameters vs Arguments:
Parameters are variables used in function definitions and arguments are the actual values we passed in function call to parameters.
Function Definition:
Functions can be defined either by function declaration or by function expression
- Function Declaration
Function declaration defines a function with an identifier and its specified parameters
function calcArea(width, height) {
return width * height;
}
console.log(calcArea(4, 6));
// expected output: 24
- Function Expression:
Function expression defines an anonymous function without identifier, mostly stored in variables.
var getArea = function(width, height) {
return width * height;
}
console.log(getArea(3, 6));
// expected output: 18
ES6 introduced a new and shorter syntax for defining function expressions, which you can explore in my next article “Arrow functions”.
Note: Functions can also be defined by Function constructor, you can read more about it here…