JavaScript has evolved into a mainstream language over a decade. The amount of flexibility that JavaScript provides has made it into a powerful language.
In JavaScript, almost everytime a piece of code is written, it's usually written inside a function. Most of our code execution is a result of function invocation. To better understand the functions, we need to look at some of the features of the JavaScript Objects. Javascript Objects can:
- be created with literals
- be assigned to variables, arrays, and properties of other objects
- be passed to the functions as arguments
- have properties
- be returned as value
Well, JavaScript function can do all that the Object can, with an addition of having the capability to be invoked. We can safely say that JavaScript Functions are objects, that can be:
- created with literals:
function myFunc() { };
- assigned to variables, arrays, and properties of other objects:
var myFunc = function() { };
myArray.push(function() { });
myObj.myFunc = function() { };
- passed as an argument to other function:
function myFunc(someFunc) {
someFunc();
}
myFunc(function() { });
- have properties:
var myFunc = function() { };
myFunc.someProperty = "George";
- returned as value:
function myFunc(){
return function() { };
}
Defining JavaScript Functions
Functions in JavaScript can be defined in a number of ways.
Function Declaration and Function Expression
Two of the most common ways a function could be defined in JavaScript is via Function Declaration and Function Expression. Function Declaration takes the function
keyword followed by the function's name along with the parenthesis for function parameters and opening and closing curly braces, like:
function myFunc() {
return "Function Declaration";
}
On the other hand, Function Expression works like any expression written in JavaScript with just the function keyword along with function parameters and the function body, like:
var myFunc = function() { return "Function Expression"; };
Immediately Invoked Function Expressions
As the name suggests, functions defined as Immediate Functions are evaluated as soon the expression is written. The IIFE mimic the module development in JavaScript:
var sum = (function (param1, param2) { return param1 + param2; })(2,3);
Arrow Functions
Arrow Functions are an ES6 addition of JavaScript. They can be seen as a simplification to the Function Expressions by adding syntactic sugar to it. Arrow Functions are defined with fat arrow sign =>, like:
var var1 = name => "Hi " + name;
var var2 = var1("George");
In case there is no parameter for the function, an arrow function can be defined as:
var myFunc = () => alert('Arrow Function Invoked');
In the next article, I will try to explain the implicit parameters that the JavaScript Function has.