Skip to content

JavaScript Functions πŸš€ΒΆ

Prerequisites: JavaScript Variables

Mentor's Note: A function is a "Recipe." You write it once, and then you can cook that dish (run that code) whenever you're hungry, just by calling its name! πŸ’‘


🌟 The Scenario: The Coffee Recipe β˜•ΒΆ

Imagine you have a specific way you like your coffee.

  • The Logic:
    • Ingredients (Parameters): 1 spoon Coffee, 2 spoons Sugar. πŸ“¦
    • The Process (Body): Mix with hot water, stir well. βš™οΈ
    • The Result (Return): A hot cup of coffee. β˜•
  • The Result: Instead of explaining the process every morning, you just tell your assistant: "Make Coffee." βœ…

πŸ“– Concept ExplanationΒΆ

1. Function DeclarationΒΆ

You define a function with the function keyword.

function greet(name) {
  return "Hello " + name + "! πŸ‘‹";
}

2. Parameters vs. ArgumentsΒΆ

  • Parameters: The "Placeholders" in the definition (name).
  • Arguments: The "Real Data" you pass when calling ("Vishnu").

3. Function Scope (The "Private Room") 🧱¢

Variables created inside a function are Local. They cannot be seen or used by the rest of the world outside that function.


🎨 Visual Logic: The Function Machine¢

graph LR
    A[Input: 5, 10 πŸ“₯] --> B[Function: Addition Machine βš™οΈ]
    B --> C[Output: 15 πŸ“€]

πŸ’» Implementation: The Function LabΒΆ

// πŸ›’ Scenario: Calculating a Discount
// πŸš€ Action: Using parameters and return

function calculateTotal(price, discount) {
    let finalPrice = price - discount;
    return finalPrice;
}

let myBill = calculateTotal(100, 20);
console.log(`Final Bill: β‚Ή${myBill} βœ…`);
// πŸš€ Action: The "Short-cut" way (ES6)
const multiply = (a, b) => a * b;

console.log(multiply(5, 5)); // 25

πŸ“Š Sample Dry RunΒΆ

Step Action price discount Result
1 Call calculate(100, 10) 100 10 Waiting...
2 Calculate 100 - 10 -- -- 90
3 return 90 -- -- 90 sent back! βœ…

πŸ“ˆ Technical AnalysisΒΆ

  • Hoisting: Function declarations are moved to the top by the browser. You can call a function before you define it! (But don't do this, it's messy). ⏱️

🎯 Practice Lab πŸ§ͺΒΆ

Task: The Area Master

Task: Write a function getArea(length, width) that returns the area of a rectangle. Bonus: Try writing it as an Arrow Function. Hint: length * width. πŸ’‘


πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers love asking about Anonymous Functions. These are functions without a name, often used as callbacks (e.g., button.onclick = function() { ... })!"


πŸ’‘ Pro Tip: "Computers are good at following instructions, but not at reading your mind. Be precise with your functions!" - Donald Knuth


← Back: Data Types | Next: Objects β†’