Table of contents
A function is an essential building block of a program, also a program is a set of instructions assigned to a computer to produce an output. function defines processes, groups thems and makes them reusable. In extensive programs, function structure programs into subprograms that can be independent of each other. A function is a critical component in driving a computer program.
In this write-up, we will take a look at the javascript function, why it is important and how it can be used effectively for program development.
What you will learn:
- Function definition
- Function invocation
- Function scope
- Function stack (call stack)
- Arrow function
- Closure
- Recursion
- Function and Side Effect
Let's dive in
Function Definition
This seems easy until you are in developing a program then you have to critically think about how to define one. Note the following while defining a function: Naming, Parameter, and Statement.
A function name starts with a function keyword, and a descriptive name, naming in programming 🤣 is one of the most difficult problems in computing someone said that though 😟 . Based on the general naming standard, it is best to give a descriptive name, that explains the function action.
A function Parameter is a variable passed to a function, which is in open and closed bracket(), and can have more than one, separated by commas or none. Finally the function statement the code block in a curly bracket, it is a list of steps for the program flow and a return statement for the code output.
Look at the image below
Img source: Google
Function Invocation
To invoke a function is to call a function to execute its predefined action, i.e to make it do something. It is best to recall that function definition does not execute the function, calling a function does. Many developers forget this oftentimes, then debug all day. Ensure to call your function
Function Scoping.
I will better let you know, we will be visiting English Oxford Dictionary to get some understanding.
Scoping is the present participle of scope, well scope is defined as the extent of the area or subject matter that something deals with. synonymous to words the reach, the range, the span, the limit to which a thing can exist.
Function scoping is a set space or limit to which you can access a variable. Function scope is when variable is only accessible within the function body where it's declared. Already we have two popular know types of scope. The global scopes and the local scope.
The global scope is general access to variables outside a function.
The local scope is restricted access to variables inside a function.
However, a nested scope exists where code of block and function are into another, in multiple instances. Variable declare outside can be accessed inside a function but it can't be the opposite.
Let me explain better a child can inherit certain attributes from his parent, but the parent can't inherit from the child, same as the grandchild inherits from a child and child for a parent.
Function stack
Every program has a control flow structure, in the old paradigm it is procedural, now code blocks can be skipped or held still a certain code(function) has completed its execution. How does the computer remember this? The computer uses the call stack mechanism to track scripts calling multiple functions.
function salute() {
console.log("bim");
Hi();
console.log("kale");
}
function Hi() {
return "Hi!";
}
// Invoke salute function
salute();
A Call stack invokes salute
, starts the function salute
encountered Hi
, stores Hi
at the top of the stack, stop the execution of salute
, and processes Hi
, When a function returns, it removes the top context from the stack and uses that context to continue execution with "salute".
Storage happens in the memory when the stack is overloaded it reports a statement like "out of stack" or "stack overflow".... maybe this is how Stack Overflow platform got its brand name....
🤣ah ah ah jokes anyways.
Stack Overflow Platform is a question and answer website for professional and enthusiast programmers, check out bug solutions, it helps a lot in case you get stuck.
Arrow function
Arrow function rewrites the normal way of writing regular functions with shorten syntax and does not have its own this
. A = and > is added to create the arrow = > follow by a function body.
const mutiply = x => x * x; //one parameter
const add = (a, b) => { return a + b; }; //two parameters
Closure
A closure is a combination of function and its environment. Closure gives access to the outer function from the inner function, it is as simple as a variable declared in an outer function can be accessed in an inner function. A closure functions in scoping mechanism, it remembers the environment in which it is created.
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(7); // Remember it environment
console.log(twice(2));
Recursion function
This is a function calling itself. A recursive function must have a condition to terminate it at a point in time, otherwise, the function run indefinitely.
function power(base, exponent) {
if (exponent == 0) { //condition that cause the repeat break
return 1;
} else {
return base * power(base, exponent - 1); //self call happens here
}
}
console.log(power(2, 5));
Function and Side Effect
Function are fundamental design such that a declaration on it returns a value(output) or side Effect.
What is a side effect
A functional program in which the output is not predictable, input for output is called a side effect. when the program has unpredictable behaviour and mutability it has side effects.
//array
const shoes =
['Stilettos','Spool Heels','Wedges','Brogues','Loafers','Ballerinas']
//side effect
function removeShoe(shoes){
return shoes.shift() // it removes the first element
}
console.log(removeShoe(shoes))
console.log(shoes)
// The side effect show that if we plan to reuse the same code in future,
// Its impossible because
// the original state of the code has already been modified.
To avoid side effects use a pure function
What is Pure Function
A pure function is a function that produces the same output without side effects and does not rely on the function side effect, even if it is a mutating variable.
// Avoiding side effect
const shoes =
['Stilettos','Spool Heels','Wedges','Brogues','Loafers','Ballerinas']
function removeShoe(shoes){
const newShoes = [].concat(shoes);
newShoes.shift()
return newShoes
}
console.log(removeShoe(shoes)); // shoe array remove first item
console.log(shoes); //shoe array is not modified
What is Non Pure Function or Impure function
This is a function that has one or more side effects. it produces different output for the same input, it works with a mutation that alters the state of returning the value.
const shoes =
['Stilettos','Spool Heels','Wedges','Brogues','Loafers','Ballerinas']
function updateShoe(newShoe) {
shoes.push(newShoe);
return shoes;
}
console.log( updateShoe('Open toes')); // modify shoes state
In the snippet above, updateShoe() is an impure function because it contains code (newShoes) that mutates an external state shoe[] — which gives updateShoe() some side effects.
Quality of a good function
- A Function should perform a single task e.g addToCart() it adds items to the cart only.
- A Good function should be predictable, the same input for the same input.
- A good function must have a good return statement and no side effects.
- A good function must be immutable, the state of data does change.
Conclusion
Great software is made with quality functions, separating the tasks of your program in a reusable and organised structure. You engage yourself in standard practices if writing code doing the DRY method, don't repeat yourself. Function helps to avoid repetition.
Engage in writing quality code!
I will be glad you engage this post, with comments.
I hope you find this helpful.
keep living.