Table of Contents
What are JavaScript functions?
Functions are one of the main building blocks In JavaScript. Functions can have different syntaxes. In this post, we are going to look at some useful points that every developer should know.
The function is a statement that takes an input, makes use of those input/inputs, and returns a useful output.
This is NOT a function. But, a procedure
function greeting(){
console.log(“Hello World”)
}
This is function
function greeting( str ){
return str;
}
Is function an object?
Simply, the function is an object in JavaScript. It is a Function object. But, probably, you may have never used a Function constructor to create a function object as follows:
const print = new Function(‘str’, ‘return str’);
console.log(print(“hello world”))
This will create the print function dynamically. However, creating a function like this is not recommended due to a lack of security. Therefore, most JavaScript programmer uses the function keyword to declare a new function.
As I mentioned before every function in JavaScript is an object. You can test this statement in the console
(function(){}).constructor === Function
This should return true
Function declaration & functional expression
A function declaration is as follows
function add( num1, num2 ) {
return num1 + num2;
}
A functional expression is slightly different
Functional expression is a statement that does not begin with the keyword function.
const add = function(num1, num2) {
return num1 + num2;
};
or
const getTotal = function add(num1, num2) {
return num1 + num2;
};
An important thing to note is that while functional declarations must have a name, Only function expressions may or may not have a name (ex, anonymous functions, IIFE ).
Calling functions
after declaring a function, you must call it for execution. The executing function should be in scope(scope determines the accessibility )when it is called.
It is not necessary to call a function after function declaration. you can call it before the function declaration. This is called hoisting in Javascript.
function displayName( name ){
console.log( name );
}
/*
any other code
*/
displayName("Dinesh");//call function
displayName("Dinesh"); //call function;hoisting at work
/*
any other code
*/
function displayName( name ){
console.log( name );
}
Function hoisting works only for function declarations, and NOT for functional expressions.
displayName("Dinesh");
//call function. ReferenceError: Cannot access 'displayName' before initialization
const displayName = function ( name ){
console.log( name );
}
Scope of functions ( or procedures )
A function creates a scope. What is the scope of a function?
In simple terms, it means the extent a function as its “Influence”, or the current context of code. it is the availability or the accessibility.
If you define a variable inside a function, it is available only to that function. It is a private variable(it is in the local scope ) of that function.
let first_name = "Dinesh" //first_name is in global scope
function displayName(){
let last_name = "Gamage"
//last_name is local to displayName function. You can not use it in global
scope
console.log( `${first_name } ${last_name}` );
}
displayName();
Different uses of functions
Depending on the use, functions can be called various types of names.
Inner functions and outer functions
a function that is defined inside another function is the inner function( nested function ), and the container of that function is the outer function.
function getInput( num1 , num2 ){ //outer function
let total = 0;
function calculate (){ // the inner function
total = num1 + num2;
return total;
}
console.log( calculate() )
}
getInput( 2, 3 );//calling the outer function
Recursive functions
If a function is called inside itself it is called and recursive function. Recursive functions can act as loops. Recursion has different applications and knowledge of function stack critical in this regard.
A typical recursive function should look as follows
function recurse() {
if(condition) {
// stop calling itself
//...
} else {
recurse();
}
}
function factorial(num ) {
if (num == 0) {
return 1;
}
return num * factorial(num - 1);
}
Anonymous functions
Simply, it is function without a name.
There are situations where you may not need to have a name for a function. These functions are collectively named anonymous functions. Following are some of the uses.
- function expression ( As mentioned above )
const total = function(num1, num2) { return num1 + num2 };
- Arrow functions
Introduced in ES6, the arrow function eliminates the need to use both function keyword and name. Often used as a function expression.
const total = ( num1, num2 ) => num1 + num2;
- Immediately Invoked Function Expression
Syntax:
(function() { statements })();or as an arrow function
(( ) =>{ statements } )();(function( num1 , num2 ) {
console.log( num1 + num2 );
})(2,3);
IIFE executes as soon as it is declared.
Closures
As mentioned before the inner function is a function that has its declaration within another function (outer function). While the inner function can access arguments and variables in the outer function, the outer function can not access arguments and variables defined in the inner function.
A useful formation of this inner and outer function is closure. What is closure?
It is a situation in which the inner function becomes available to the environment outside the outer function.
Let’s see how it happens
function setName( firstName, lastName ){ //the outer function
let fullName = `${firstName} ${lastName}`;
return () => "Dear " + fullName ;
/*
the inner function accessing the “fullName” variable.
by returning the inner function, the inner function can be referenced outside the outer function. Thus inner function gains the scope of the outer function
*/
}
const getName = setName( "Abrahm","Lincon");
//call the outer function and hold a reference to the inner function
console.log( getName() ); //using the inner function outside the outer function.
An important thing to note is that the variables and functions defined in the outer function live longer than the duration of execution of the outer function.
Closure can be complex and useful code, especially, when returning an object with references to inner functions.
Summary
JavaScript functions are nothing but objects. Function declaration, functional expression, calling a function, and function scope are important aspects that every developer should know. Modern JavaScript has many forms and uses of functions. Some of the different types of functions are inner and outer functions, recursive functions, and anonymous functions. A closure is a very interesting aspect of how functions can be utilized to create complex, but useful code.