You have probably encountered the first challenge or task in your learning...create a function that does a b c .... First, we can pause and reflect on the meaning and importance of creating functions. Why do we need to create them anyway?
A function is basically a piece or rather, a "chunk" of code that can be reused over and over again. Reusing minimizes the need to write the same piece of code again, to do a specified task. In your everyday programming life, you will probably write countless functions to solve various problems.
Declaring a function in JavaScript
Basically, you should have the keyword function, which should be followed by the function name, list of parameter(s) in parenthesis and finally, the defining statements in curly brackets To illustrate that;
function functionName (parameters) {
//code to be executed
}
It is important to call or invoke a function in your program for it to be executed and get the value. To call the above function, the code would be as follows;
function functionName (parameters) {
//code to be executed
}
functionName() //calling or invoking a function
Declaring functions without parameters
This type of a function has no passed argument in the parenthesis. Inside the block of code, everything is stated and returned.
The following function gets the cube of a number
function cube() {
let a = 3
let cb = a * a * a
console.log(cb)
}
cube() // Returns the cube of 3 (27)
Declaring functions with parameters
Using the above example, let us change the function to have some parameters.
function cube(a) {
let cube = a * a * a
return cube
}
console.log (cube(3)) // Returns the cube of 3 (27)
The parameter value is stated as 3 and the result returned is the cube of 3. It is important to note that only one parameter was used in this example. How about a situation where you have to deal with multiple parameters?
Functions with multiple parameters
Assume a situation where you have to find the volume of a cuboid
The function can be declared as follows;
function volumeCuboid (length, width, height) {
let volume = length * width * height
return volume
}
console.log(volumeCuboid(4,5,6)) //returns 120
There are other types of functions in JavaScript that you may probably encounter. They include the following;
- Arrow functions
- Anonymous functions
- Expression functions
I will discuss them in my next post.