How to Write Functions in Javascript
There are broadly 3 ways to create a function call.
1) The simplest form — Function Declaration
Function declaration is the simplest form of writing a function.
//Function Definition
function greet(){
console.log("Namastey");
}
//Function Call
greet();
This will simply print the text “Namastey” to console.
First-Class Functions
In Javascript we have what are called the first-class functions. First-class functions are objects themselves and are treated like any other variable. For example, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
Let’s take a look.
//Function Def
function greet(){
console.log("\nNamastey\n");
}
//Function Call
greet();
//First Class Function Example
function first_class_greeting(fn){
//fn is passed as an argument
//But it is called as a function
fn();
}
//greet function is passed as any object would be
first_class_greeting(greet);
So the Namastey is printed twice.
Another way of doing the same thing is to pass an anonymous function as an argument
first_class_greeting(
function(){
console.log("Ni Hao");
}
)
2) Function Expressions
The second way of creating functions in Javascript is by the way of creating function-expressions. When the function is created as a part of an expression, it’s called a “Function Expression”.
Let’s see an example.
//Function expression
var greetExpression = function(){
console.log('Bonjour');
}
greetExpression();
Hoisting
Hoisting is JavaScript’s default behaviour of moving declarations to the top i.e. you can access a function or a variable before it is even declared in the code. Hoisting is when a function/variable can be accessed before its code appears in the execution. This is where function expressions differ from function declarations.
This is where function expressions differ from function declarations.
The main difference between function declarations and function expressions is that Function Declarations can be accessed processed before the code block is executed. They are visible everywhere in the block.
Function Expressions are created when the execution flow reaches them and therefore cannot be accessed before themselves.
Difference
console.log(checkHoist) // This throws - undefined
checkHoist(); // Throws - TypeError: checkHoist is not a function
//Function Expression
var checkHoist = function() {
console.log('Am I Hoisted?');
};
This is very different from how function declaration would behave.
console.log(checkHoist2)
checkHoist2();//Function Declaration
function checkHoist2() {
console.log('Am I Hoisted?');
};
2) IIFE — Immediately Invoked Function Expressions
IIFE is a function expression that automatically invokes after completion of the definition. These functions are called the moment the execution flow reaches their position. One doesn’t need to explicitly call these functions.
The most important utility of IIFE’s is that they limit they protect the scope of the variables defined inside them.
It is commonly known that a function in JavaScript creates local scope. However, sometimes one ends up accidentally polluting the global variables unknowingly. IIFE’s are a protection against such mistakes. Fun Fact — NodeJS executes a user’s complete code as an IIFE passed to the V8 Engine!
NodeJS executes a user’s complete code as an IIFE passed to the V8 Engine!
Let’s take a look at an example.
(function (num1, num2) {
var sum = num1 + num2;
console.log("The sum of " + num1 + " & " + num2 + " is = ", sum);
})(10,15);
Basically the structure of an IIFE is like this. It is essentially an anonymous function wrapped inside a pair of parenthesis.
(function () { //Your js code goes here });
If your function accepts parameters they go into an additional pair of parenthesis at the end of the IIFE.
There are a couple of other ways of declaring functions but these are the most frequently used ways. Try using functions for your Javascript code and let me know if you stumble.