JavaScript Functions
When developing an application, you often need to perform the same action in many places. For example, you may want to show a message whenever an error occurs.
To avoid repeating the same code all over places, we can use JavaScript functions.
There are mainly two advantages of JavaScript functions.
- Code reusability: We can call a function several times so it save coding.
- Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.
Below are the different ways to create functions in JavaScript.
Types | Example | Explanation |
Variable Assignment | // Named var sum = function add(num1,num2) { return num1 + num2; }; // Anonymous var sum = function(num1, num2) { return num1 + num2; }; | This is functionally equivalent to the Function Declaration above, except this variation is NOT hoisted. The name of our function (add) cannot be called directly (see below), but it can come in handy when debugging: sum(1,1); // returns 2 add(1,1); // “add is not defined” |
Immediately Invoked | // Named (function sum(num1, num2) { return num1 + num2; }(1, 2)); // Anonymous (function(num1, num2) { return num1 + num2; }(1, 2)); | This function is immediately invoked, meaning that it is defined and called at the same time. The function’s name is only available within its execution scope (defined by the parentheses), so it cannot be called later in the program. sum(1,1); // “sum is not defined” Immediately invoked functions can be used to encapsulate a program, preventing it from polluting the global namespace. |
Assigned and Invoked | // Named var sum = function add(num1, num2) { return num1 + num2; }(1, 2); // Anonymous var sum = function(num1, num2) {return num1 + num2; }(1, 2); | This is a combination of the variable assignment expression and the immediately invoked function (both demonstrated above). One neat application for the named variety of this is to make recursive functions more readable, by substituting arguments. |
Property Assignment | // Named var obj1 = { sum: function add(num1, num2) { return num1 + num2 } }; // Anonymous var obj2 = { sum: function(num1, num2) { return num1 + num2 } } | By assigning functions (either named or unnamed) to properties of objects, we define methods on those objects. This has many applications in object oriented programming. We can also use this to namespace our functions, and keep them out of the global scope. Here’s how we would call the methods defined in the examples: obj1.sum(1, 2); // returns 3 obj2.sum(1, 2); // returns 3 |
Passed As Argument | // Named window.setTimeout(function add() { alert(1 + 2); }, 500); // Anonymous window.setTimeout(function() { alert(1 + 2); } 500); | Function names in ECMAScript are nothing more than variables, meaning we can pass them around like variables. Many methods (like setTimeout()) take functions as arguments. This is a common pattern for defining callbacks. |
Closure | // Named function counter() { var count = 0; return function c() { alert(count++); } } // Anonymous function counter() { var count = 0; return function() { alert(count++); } } | Functions can be returned from other functions. This lets us do clever things like the following (picking up from the example): var bob = {}, rob = {}; bob.count = counter(); rob.count = counter(); bob.count(); // alerts “0” bob.count(); // alerts “1 rob.count(); // alerts “0” rob.count(); // alerts “1” Each person can increment their own count variable despite the fact that it originated outside the scope of the count() function. This is called a closure. |
Arrow Functions | / There is no “named” // form of this function. // Anonymous var sum = (num1, num2) => { return num1 + num2 }; // Anonymous w/out optional // bracketed return var sum = (num1, num2) => num1 + num2; | Arrow (or “fat-arrow”) functions are newly introduced as part of the ES6 specification. As such, they are only implemented in the most modern browsers (check a compatibility table for specifics). This example: var sum = (num1, num2) => { return num1 + num2 }; is functionally equivalent to: var sum = function(num1, num2) { return num1 + num2; }; Arrow functions are function expressions, and as such, they are usable in all the contexts shown above (variable assignment, passed as an argument, etc.). |
Traditional Way | function functionName(parameters) { code to be executed } |