๐Ÿ“Œ Understanding JavaScript Functions: A Beginner's Guide ๐Ÿš€

๐Ÿ“Œ Understanding JavaScript Functions: A Beginner's Guide ๐Ÿš€

ยท

4 min read

function:โ€”> ye ek block of code hota hai jo sirf tab he execute hota hai jub usse call kiya jaye

// Function syntex 
function functionName(parameters) {
    // Function body
    return result; // (optional)
}

// Function call
functionName(arguments);

๐Ÿ”ฅ Function Ka Code Mein Use ๐Ÿ’ป๐Ÿš€

JavaScript mein functions ka use code ko reusable, clean aur modular banane ke liye hota hai. Yeh alag-alag tasks ko handle karne, DRY (Don't Repeat Yourself) principle follow karne, aur better debugging ke liye kaam aate hain.

// Function to find square
function getSquare(n) {
    return n * n;
}

// Function to find cube
function getCube(n) {
    return n * n * n;
}

// Function Calls
console.log("Square:", getSquare(4)); // Output: 16
console.log("Cube:", getCube(4));     // Output: 64

Dekha! Function ka use karke code zyada readable aur reusable ho gaya. Ab agar kisi aur number ka square/cube chahiye toh bas function call karna padega! ๐Ÿ˜Ž๐ŸŽฏ


โš”๏ธ Function Declaration vs Function Expression in JavaScript ๐Ÿš€

JavaScript mein functions likhne ke do main tareeke hote hain:

1๏ธโƒฃ Function Declaration
2๏ธโƒฃ Function Expression

Dono ka kaam ek hi hota hai, lekin inke behavior mein kuch important differences hote hain. Chalo ek-ek karke samajhte hain!

๐Ÿ“ 1. Function Declaration

๐Ÿ‘‰ Definition: Yeh ek named function hota hai jo hoisting support karta hai, yani function ko define karne se pehle bhi call kar sakte ho

โœ… Syntax:

function greet() {
    console.log("Hello, world!");
}

// Function call
greet(); // Output: Hello, world!

โœ… Hoisting Example:

sayHello(); // Works even before declaration!

function sayHello() {
    console.log("Hello from Function Declaration!");
}

๐Ÿ“ 2. Function Expression

๐Ÿ‘‰ Definition: Jab function ko ek variable mein store kiya jata hai, toh use function expression kehte hain. Yeh hoisting support nahi karta.

โœ… Syntax:

const greet = function() {
    console.log("Hello, world!");
};

// Function call
greet(); // Output: Hello, world!

โŒ Hoisting Issue:

sayHi(); // โŒ Error: Cannot access 'sayHi' before initialization

const sayHi = function() {
    console.log("Hello from Function Expression!");
};

๐Ÿ”ฅ Closure Kya Hota Hai?

๐Ÿ‘‰ Closure ek aisa function hota hai jo apne parent function ke scope ko yaad rakhta hai, chahe parent function execute ho chuka ho.

Matlab ek function ke andar jo inner function hota hai, wo bahar wale function ke variables ko access kar sakta hai, even after the parent function has finished execution. Yehi closure ka magic hai! ๐Ÿ˜Žโœจ

โœ… Closure ka Basic Example

function outerFunction() {
    let message = "Hello, I am a Closure!"; // Parent function ka variable

    function innerFunction() {
        console.log(message); // Inner function, parent ka variable access kar raha hai
    }

    return innerFunction; // Inner function ko return kar diya
}

const myClosure = outerFunction(); // outerFunction execute ho chuka hai
myClosure(); // Output: Hello, I am a Closure! (But kaise? Closure ki wajah se!)

๐Ÿง Kaise Kaam Karta Hai?

1๏ธโƒฃ outerFunction ek variable message create karta hai.
2๏ธโƒฃ innerFunction us message variable ko access karta hai.
3๏ธโƒฃ Jab outerFunction execute ho jata hai, normally uska message variable delete ho jana chahiye.
4๏ธโƒฃ Lekin Closure ki wajah se, innerFunction us variable ko yaad rakhta hai! ๐Ÿ’ก


๐Ÿ”ฅ Arrow Function

Arrow functions (=>) JavaScript ke modern aur short syntax wale functions hain, jo ES6 (ECMAScript 2015) me introduce kiye gaye the. Yeh concise syntax, lexical this binding, aur cleaner code likhne ke liye use hote hain.

โœ… Arrow Function Syntax

const functionName = (parameters) => expression;

Example:

const add = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

โœ”๏ธ Automatic return (agar ek line ka function ho)

โœ…Arrow Function Without Parameters

const sayHello = () => console.log("Hello, World!");
sayHello(); // Output: Hello, World!

โœ…Arrow Function with Single Parameter (No Parentheses Needed)

const square = num => num * num;

console.log(square(4)); // Output: 16

โœ…Arrow Function in setTimeout (Lexical this) javascript Copy Edit

const user = {
    name: "Rahul",
    greet: function() {
        setTimeout(() => {
            console.log(`Hello, ${this.name}!`);
        }, 1000);
    }
};

user.greet(); // Output: Hello, Rahul! (after 1 sec)

โœ”๏ธ Arrow function ka this parent scope se leta hai (lexical this binding).

โœ…Arrow Function in Array Methods (map, filter, reduce)

Arrow functions higher-order functions ke sath perfect kaam karte hain!

const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]

// Filter even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]

// Sum of all numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15

โŒ Arrow Function ke Limitations

1๏ธโƒฃ this keyword ko override nahi kar sakta (Lexical this)
2๏ธโƒฃ arguments object nahi hota (Instead, use rest parameters (...args))
3๏ธโƒฃ new keyword ke sath use nahi ho sakta (Arrow functions constructor nahi bana sakte)

const obj = {
    name: "Amit",
    normalFunction: function() {
        console.log(this.name); // Works: "Amit"
    },
    arrowFunction: () => {
        console.log(this.name); // Undefined (Lexical this)
    }
};

obj.normalFunction(); // Output: Amit
obj.arrowFunction(); // Output: undefined

The endโ€ฆ

ย