Functions :- Building Blocks of JavaScript
All about the functions of JavaScript that a programmer should know !
While writing code do you ever came across a problem where you have to do a same task repeatedly at different levels in your program/code. Obviously, you are not going to write the same code for more than one time. If we do so, then it is against the basic rule of coding which is ( Do not repeat yourself ). So, how can we solve this problem ? Well, JavaScript has a amazing building block to solve this problem known as Function. So, lets’ s see all the basic thing about the function ( core building block of javascript ) in detail.
Functions
Functions are the one of the most fundamental building blocks of the javascript. These are basically the blocks of code designed to perform a particular task.
A function in javascript is similar to procedure - a set of statements that performs a task or calculates a value. Like a program itself, a function is also composed of sequence of statements called body of the function. Values can also be passed to the function as a parameter and the will return a value.
Example :- A calculator is considered as function where calculator is the name of the function and the Addition, Subtraction, Multiplication and Division are the tasks performed by the function.
The below is the flowchart of how the function is called and executed in JavaScript :-
Defining Functions
Defining a function means creating reusable block of code the performs a specific task and calculates a value when called. There are three most common and popular ways to define a function in JavaScript which are :-
Function Declaration
Function Expression
Arrow Function
Let’s understand each of them in detail..
1️⃣ Function Declaration
A function definition ( also called a function - declaration or function statement ) consist of function
keyword followed by :- Name of the function, a list of parameters to the function and the body of the function ( or you can say statements ), enclosed in curly braces ( {}
).
The syntax of Function declaration is :-
function function_name ( Parameters ) {
// Statements of=r body of the function
}
Consider the following example :-
function Print () {
console.log("Hello World!" );
}
Print(); // Calling or invoking the function
// Output :- Hello World!
In above code, we define a function which is printing the “Hello World!” whenever we call it. This is how function is defined using the Function Declaration.
Characteristics :-
Hoisting :- Function declarations are hoisted to the top of their scope, so they can be used before they are defined.
Can be used globally ( if defined inside the global scope ).
Example of hoisting :-
Print(); // Works because function declaration is hoisted function Print() { console.log("Hello, world!"); }
2️⃣ Function Expression
Function Expression means defining a function inside an expression using function keyword. In simple words, defining a function same as Function Declaration but assigning it to a variable.
The main difference between the function expression and function declaration is the function name, which can be omitted in function expression making it as a anonymous functions.
The syntax of the Function Expression is also very similar to the Function Declaration. The syntax is :-
const variable_name = function ( parameters ) {
// statements or body of the function
};
Consider the following example of the Function Expression :-
const Print = function () {
console.log("Hello World!");
};
Print();
// Output :- Hello World!
Characteristics :-
No hoisting :- Means, you cannot call the function before its declaration like you are doing in Function Declaration.
Can be anonymous :- The function can be assigned to a variable making the function anonymous.
NOTE :- The arrow function is defined later in the article !
Difference Between The Function Declaration and Function Expression
The following table describe the the main difference between the function expression and function declaration.
Feature | Function Declaration | Function Expression |
Syntax | function function_Name() {} | const functionName = function() {} |
Hoisting | Yes (can be called before declaration) | No (must be defined before use) |
Named Function | Always has a name | Can be anonymous or named |
Usage | Typically used for defining reusable functions | Common in callbacks, closures, and IIFE |
Calling a Function
Defining a function does not execute it. Defining means, naming the function and specifies what to do when the function is called.
Calling the Function actually perform the specified action with the indicated parameters. This means, the execution of function happens when the function is called explicitly. Consider the following example :-
function add(a, b) {
console.log(`The sum of a and b is: ${a + b}`);
}
add(5, 5); // Calling the add function with the required parametrs
// Output :- The sum of a and b is: 10
Function Scope
Function form scope for variables - this means the variables defined inside a variable cannot be accessed from anywhere outside the function. The function scope inherits all upper scopes. This means a function defined inside the another function can also access the all variables defined inside it’s parent function. On the other hand, parent function does not have access to the variables defined inside the inner function. This is called the scope of the function.
We can also consider scope as the boundaries inside which we can access the variable.
let global_var = "I am global"; // Accessable from everywhere
function Print() {
let local_var = "I am local"; // Can only be accessed wutin the function
// console.log(child_var); // Parent cannot access it's child's variable
function child() {
let child_var = "I am child";
console.log(local_var); // Can access the variable from it;s parent function
}
child();
}
// console.log(local_var); // Cannot be acceasble outside the function
Print();
Closures
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In simple word, a closure gives a function access its own scope, outer scope’s variables, and global variables, even after the function has finished execution. Closures allow function to “remember” data across multiple calls.
Closures are work upon Lexical Scoping. So, we need to first understand the lexical scoping in order to understand the Closures.
Lexical Scoping :-
Lexical Scoping is the fundamental concept in JavaScript that determine the accessibility of variables and function based upon where they are defined in the source code. In simple terms, lexical scope is the scope of a variable or function determined at compile time by its physical location in the code. JavaScript uses lexical scoping to decide which variables are accessible to a function during its execution.
Lexical scope is a static and remains same throughout the program execution. This allows inner function to access the variables from their outer functions. Consider the following function for proper understanding of the Lexical Scoping :-
function outer() {
var name = "Brave";
function inner() {
console.log(name); // accessing the outer function's variable
}
inner();
}
outer();
// Output :- Brave
Run the above code, and you will see that the inner()
function will display the value of the variable name
successfully. This is the example of the Lexical scoping, which determine how the values are resolved when the function are nested.
Now, let’s see the example of Closures. Consider the following code in which we declare and a count variable in the parent function and returned and anonymous function.
function counter() {
let count = 0;
function increase() {
count++; // Remembring the outer function's varaible
console.log(count);
};
return increase;
}
const increment = counter();
increment(); // 1
increment(); // 2
increment(); // 3
At first glance, the above code might seem you unintuitive that this code still works. In some programming languages local variable within the function exist for just the duration of the function. You might expected that once the counter()
finishes it’s execution the variable would no longer be accessible. However, this is not the case in JavaScript.
This is because the functions in javascript form closures .In this case, increment is the reference to instance of the function increase()
that is created when counter()
is run. The counter function has the access to the variable count
of the parent function. Also, say that the variable counter exists in the lexical environment of the increase()
function. SO, the whole lexical environment is passed to variable increment.
This is the reason whenever we invoke the increment
variable the count
variable is available for call. This is the simplest example of the closures.
Arrow Function ( =>
)
An arrow function is shorter syntax to write functions in javascript. This is a alternative to a traditional function expression with some semantic differences which are following as :-
Arrow function do not have their own bindings like this etc.
Arrow function cannot be used as constructor and give TypeError when written with
new
keyword.
Despite their differences the arrow functions are very useful to write the small function in tow or three lines. The =>
symbol is used to declare the arrow function. The syntax of the arrow function is :-
// Arrow Function Syntax
const functionName = (parameters) => expression {
// function body
};
Consider the following example in which we are going to print the sum of a and b with the function expression and Arrow Function.
With Function Expression:-
const add = function (a, b) {
return a + b;
};
console.log(add(5, 7)); // Output = 12
With arrow function :-
const add1 = (a, b) => a + b;
console.log(add1(5, 7))
The above code works because if we have to return only single value we don’t need to write curly braces and return as arrow function has return by default. So, this is the basic example of the arrow functions in JavaScript.
Conclusion
So, Function in JavaScript are the basics building blocks that helps us to do a repetitive task at different position in the code without writing the same code again and again. I hope this article helps you to learn the basics of the function in js. If yes!, then please do like my article and suggest me any changes in the comment section. So, that’s it for today…. Bye all !