𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀
You need to know how functions work to write clean code. JavaScript offers different ways to define and use them.
Here are the main types:
Named Function You give the function a specific name. This makes it easy to call later. Example: function greet() { return "Hello!"; }
Anonymous Function These functions do not have a name. You often assign them to variables. Example: let greet = function() { console.log("Hello!"); };
Function Expression You store a function inside a constant or a variable. Example: const add = function(a, b) { return a + b; };
Arrow Function These provide a shorter syntax. They are part of ES6.
- Single parameter: x => x * x
- Zero parameters: () => "Hello"
- Multi-line: Use curly braces and the return keyword.
IIFE (Immediately Invoked Function Expression) These run the moment they are defined. You use them to avoid polluting the global scope. Example: (function() { console.log("Run!"); })();
Callback Functions A callback is a function passed into another function as an argument.
- Synchronous Callbacks: These run one after another in order.
- Asynchronous Callbacks: These run after a task finishes. For example, setTimeout runs a task after a specific delay.
Think of a restaurant. You order food. You give your number. The restaurant calls you when the food is ready. The call is the callback.
Code example: function orderFood(callback) { console.log("Preparing food..."); callback(); }
function callCustomer() { console.log("Food is ready!"); }
orderFood(callCustomer);
Understanding these patterns helps you write better logic.
Source: https://www.geeksforgeeks.org/javascript/functions-in-javascript/ Source: https://www.w3schools.com/js/js_callback.asp Full post: https://dev.to/ezhil_abinayak_e38eec8fb/types-of-functions-in-javascript-3lhl