𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
Functions help you organize code. You need to know the different types to write better programs.
Named Function You give the function a specific name. You call it by that name later. Example: function greet() { return "Hello!"; }
Anonymous Function These functions have no name. You often store them in variables. Example: let greet = function() { console.log("Hello!"); };
Function Expression You assign a function to a constant or a variable. Example: const add = function(a, b) { return a + b; };
Arrow Function This is a shorter way to write functions.
- Single parameter: x => x * x
- Zero parameters: () => "Hello"
- Multi-line: Use curly braces and the return keyword.
Immediately Invoked Function Expression (IIFE) This function runs the moment you define it. It does not wait for a call. Example: (function() { console.log("I run!"); })();
Callback Functions A callback is a function passed into another function as an argument.
Synchronous Callbacks: The code runs in order. One task finishes before the next starts.
Asynchronous Callbacks: The code does not wait. JavaScript starts a task and moves to the next line. It runs the callback when the task finishes. Example: setTimeout() uses a callback to run code after a timer.
Think of a food order. You order food. The restaurant prepares it. They call your number when it is ready. The phone call is your callback.
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