|8. Functions
Chapter 8JavaScript Tutorial~1 min read

Functions

Function Declaration, Expression, Arrow Functions

Function म्हणजे code चा reusable block जो फक्त call केल्यावर run होतो. एकच calculation वारंवार लिहिण्याऐवजी function एकदा define करतो आणि जेव्हाही हवे तेव्हा call करतो.

1. Function Declaration

Function Declaration — उदाहरण

javascript
// Define करणे
function greet(name) {
    console.log("नमस्कार, " + name + "!");
}

// Call करणे
greet("Rahul"); // Output: नमस्कार, Rahul!
greet("Priya"); // Output: नमस्कार, Priya!

// Return value असलेला function
function add(a, b) {
    return a + b;
}

let result = add(10, 20);
console.log(result); // 30

2. Function Expression

Function Expression

javascript
// Function एका variable मध्ये store करणे
const multiply = function(x, y) {
    return x * y;
};

console.log(multiply(4, 5)); // 20

// ⚠️ Function Expression hoisted नसतो
// multiply(4, 5); // ❌ Error — define होण्यापूर्वी call करता येत नाही

3. Arrow Functions — Modern ES6

Arrow Functions

javascript
// Regular function
const square = function(x) {
    return x * x;
};

// Arrow function — shorter syntax
const square = (x) => {
    return x * x;
};

// Single line — return implicit
const square = x => x * x;
console.log(square(5)); // 25

// Multiple parameters
const add = (a, b) => a + b;
console.log(add(10, 5)); // 15

// No parameters
const greet = () => console.log("नमस्कार!");
greet();

Nested Functions

Nested Functions — Practical Example

javascript
function calculateBill(amount, taxRate) {
    // Inner function — outer function आत
    function addTax(value) {
        return value + (value * taxRate);
    }
    return addTax(amount);
}

console.log(calculateBill(1000, 0.18)); // 1180 (18% GST सह)
  • Function Declaration: Hoisted — define होण्यापूर्वी call करता येतो
  • Function Expression: Not hoisted — define नंतरच call
  • Arrow Function: Short syntax, this inherit करतो (regular function प्रमाणे स्वतःचा this नाही)

Marathi Analogy

🍳 Analogy: Function म्हणजे recipe सारखे. "आमटी कशी बनवायची" ते एकदा लिहितो (define), नंतर जेव्हाही हवे तेव्हा recipe follow करतो (call). Parameters म्हणजे ingredients.

Key Points — लक्षात ठेवा

  • Function = reusable code block
  • Declaration: function name() {} — hoisted
  • Expression: const fn = function() {} — not hoisted
  • Arrow: const fn = () => {} — short, inherits this
  • return keyword ने value परत मिळते
0/13 chapters पूर्ण