Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.
Why Functions?
- Functions can be used multiple times, reducing redundancy.
- Break down complex problems into manageable pieces.
- Manage complexity by hiding implementation details.
- Can call themselves to solve problems recursively.
Calling Functions
After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between the parenthesis.
const mul = function (x, y) { return x * y;};console.log(mul(4, 5)); // 20Arrow Functions
Arrow functions allow us to write shorter function syntax.
// () => {....}
// without arrow functionlet greet = function() { return "Hello World!";}
// with arrow function let greet = () => { return "Hello World!";}Callback Functions
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
function greet(name, callback) { console.log( "Hi ",name); callback();}
function sayGoodbye() { console.log("Goodbye!");}
greet("Alice", sayGoodbye);
// expected output// Hi Alice// Goodbye!Anonymous Functions
Anonymous functions are functions defined without having a name on the top of the function definition line.
let show = function() { console.log('Anonymous function');};
show();IIFE
If you want to create a function and execute it immediately after the declaration, you can use IIFE (Immediately Invoked Function Expression),
// (() => {// // statements…// })();
(function() { console.log('IIFE');})();Nested Functions
In JavaScript, Functions within another function are called “Nested function.” These nested functions have access to the variables and parameters of the outer (enclosing) function, creating a scope hierarchy. A function can have one or more inner functions.
// Outer functionfunction outerFunction() { // Nested function function nestedFunction() { // Function logic here } // Call the nested function nestedFunction(); // Rest of the outer function logic}// Call the outer functionouterFunction();