9. Functions- Arrow, IIFE , Callbacks in JavaScript
Functions are reusable blocks of code that perform specific tasks
Function Statement
function hello(a){ console.log("Hello",a); // hello undefined } hello() /// function call we call function anywhere
Function Parameters: Default and Rest(…args)
Default parameters allow initializing function parameters with default values if no value is passed.
The rest parameter (
...
) allows a function to accept any number of arguments as an array.// Default parametrs function greet(name = "Guest") { console.log(`Hello, ${name}!`); } greet(); // "Hello, Guest!" greet("Alice"); // "Hello, Alice!" //If no argument is provided, "Guest" is used as the default. // Rest function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); } console.log(sum(1, 2, 3, 4)); // 10 console.log(sum(5, 10)); // 15 //...numbers gathers all function arguments into an array.
Arrow function
» It allow devlopers to create function in cleaner way as compared to regular function.
» We convert any function into arrow function
» They do not bind their ownthis
.// Regular function function fn(){ console.log("hi"); } fn(); // Arrow function //Syntax 1 let fn = () => console.log("hi"); fn(); //Syntax 2 let fn = ()=> { console.log("hi"); } fn();
Arrow Function vs Regular Function (
this
Binding)const obj = { value: 10, traditionalFunction: function() { console.log(this.value); // 10 }, arrowFunction: () => { console.log(this.value); // undefined } }; obj.traditionalFunction(); // 10 obj.arrowFunction(); // undefined
Explanation:
Arrow functions do not have their own
this
.this
inside an arrow function refers to the surrounding scope, not the object itself.
IIFE (Immediately Invoked Function Expressions)
» An IIFE is a function that executes immediately after it is defined.
» The function is wrapped in
()
and immediately invoked with()
.(function() { console.log("I am an IIFE!"); })(); // "I am an IIFE!" // IIFE with arrow fucntion (()=>console.log("Arrow IIFE"))();
arguments
Object» The
arguments
object is an array-like object available inside regular functions.» It contains all arguments passed to the function.
function showArguments() { console.log(arguments); } showArguments(1, 2, 3, "Hello"); // Output: [Arguments] { '0': 1, '1': 2, '2': 3, '3': 'Hello' }
Arrow Functions Don't Have
arguments
Use rest parameters (...args
) in arrow functionsCallback functions
Callback function is a function that is passed as an argument to another function.
function newfn (a,b , cb){ console.log(a,b); cb(); } function cb(){ console.log("I am Call Back"); } newfn(5,4,cb); // cb is an call back function /* Output 5 4 I am Call Back
Call backs using arrow function
let newfn = (a,b,cb)=>{ console.log(a,b); cb(); } let cb = ()=>{ console.log("I am call back"); } newfn(5,4,cb)
Callbacks & Asynchronous JavaScript:
» Callbacks are often used in asynchronous operations like API requests and setTimeout.
» setTimeout is a function that contain another function is called callback function
»
setTimeout()
schedules the callback function to run later.console.log("Start"); setTimeout(() => { console.log("This runs after 2 seconds"); }, 2000); console.log("End");
INTERVIEW QUESTIONS
What will be the output?
function test(...args) { console.log(args); } test(1, 2, 3); /* Output 10 20 5 10 5 15
const obj = { num: 10, arrow: () => console.log(this.num), // arrow function dont have this regular: function() { console.log(this.num); } }; obj.arrow(); obj.regular(); /*Output undefined 10
(() => { let count = 0; console.log(++count); })(); console.log(count);
Output:
1
ReferenceError: count is not defined
function execute(callback) { console.log("Executing..."); callback(); } execute(() => console.log("Callback executed!")); // The function callback() is called inside execute(). /*Output Executing... Callback executed!
function test(callback) { console.log("Start"); setTimeout(callback, 1000); console.log("End"); } test(() => console.log("Inside Callback")); /* Start End Inside Callback